package com.smart.translator.ui.device;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.smart.translator.R;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import android.location.LocationManager;
import android.app.AlertDialog;
import android.os.Build;
import android.widget.EditText;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import android.util.Base64;
import com.smart.translator.util.AdpcmDecoder;
import com.smart.translator.util.WavUtil;
import android.media.MediaPlayer;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.widget.Switch;
import android.content.SharedPreferences;
import android.widget.ArrayAdapter;
import android.content.ClipboardManager;
import android.content.ClipData;
import android.content.ComponentName;
import com.smart.translator.device.BleDeviceManager;
import com.smart.translator.service.PasteAccessibilityService;
import com.smart.translator.databinding.FragmentDeviceBinding;
import java.nio.charset.StandardCharsets;
import com.smart.translator.util.AsrWsClient;
import com.smart.translator.util.AudioResampler;
import com.smart.translator.util.DoubaoTTSManager;
import android.media.AudioTrack;
import android.media.AudioFormat;
import android.media.AudioManager;
import com.smart.translator.util.AdpcmEncoder;
import com.smart.translator.ui.device.DeviceAdapter;
import com.smart.translator.ui.device.HistoryDeviceAdapter;
import com.smart.translator.service.BleForegroundService;
import com.smart.translator.ble.BleManager;
import com.smart.translator.ble.AudioProcessor;
import com.smart.translator.util.VadDetector;
import com.smart.translator.util.VadManager;
import java.util.HashSet;
import java.util.Set;
import android.app.Activity;

public class DeviceFragment extends Fragment implements DeviceAdapter.OnDeviceClickListener, BleManager.BatteryLevelListener, BleManager.ScanResultListener {
    private static final int REQUEST_ENABLE_BT = 1;
    private static final int REQUEST_PERMISSIONS = 2;
    private static final long SCAN_PERIOD = 10000; // 10秒扫描时间
    private static final String WS_URL = "ws://qixin.yeshan.fun/ws/speech_v2";
    private static final String WS_URL_V3 = "ws://qixin.yeshan.fun/ws/speech_v3";
    private static final String PREFS_SWITCH = "switch_prefs";
    private static final String KEY_BT_SWITCH = "bt_switch";
    private static final String KEY_AUTO_CONNECT_SWITCH = "auto_connect_switch";
    private static final String KEY_AUTO_JUMP_WECHAT_SWITCH = "auto_jump_wechat_switch";
    private static final String KEY_USE_SPEECH_V3_SWITCH = "use_speech_v3_switch";
    private static final String KEY_USE_SILERO_VAD_SWITCH = "use_silero_vad_switch";

    // ⭐ 修复：移除自己的蓝牙管理对象，统一使用BleManager单例
    private BluetoothAdapter bluetoothAdapter;
    // private BluetoothLeScanner bluetoothLeScanner;
    // private BluetoothGatt bluetoothGatt;
    private Handler handler = new Handler(Looper.getMainLooper());
    private boolean isScanning = false;
    private DeviceAdapter deviceAdapter;
    private List<BluetoothDevice> devices = new ArrayList<>();
    private List<Integer> rssiValues = new ArrayList<>();

    // 新增弹窗相关成员变量
    private List<BluetoothDevice> foundWhiteListDevices = new ArrayList<>();
    private AlertDialog deviceDialog;
    private ArrayAdapter<String> deviceAdapterDialog;

    // 统一的ScanCallback实例
    private final ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            Log.d("BluetoothScan", "onScanResult回调触发");
            if (!isAdded()) {
                Log.w("BluetoothScan", "Fragment未附加到Activity，忽略扫描结果");
                return;
            }
            if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            BluetoothDevice device = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                device = result.getDevice();
            }
            int rssi = 0;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                rssi = result.getRssi();
            }
            String deviceName = device.getName();
            String deviceAddress = device.getAddress();
            
            // 打印设备信息
            android.util.Log.d("BluetoothScan", String.format("BLE扫描发现设备: %s (%s), RSSI: %d, 回调类型: %d", 
                deviceName != null ? deviceName : "未知设备", 
                deviceAddress, 
                rssi,
                callbackType));
            
            // ⭐ 修复：将扫描到的设备添加到devices列表
            boolean exists = false;
            for (BluetoothDevice d : devices) {
                if (d.getAddress().equals(device.getAddress())) {
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                devices.add(device);
                Log.d("BluetoothScan", "设备已添加到devices列表: " + deviceAddress);
            }
            
            // 新增：扫描到白名单设备即弹窗
            if (shouldAddDevice(device)) {
                boolean existsInWhiteList = false;
                for (BluetoothDevice d : foundWhiteListDevices) {
                    if (d.getAddress().equals(device.getAddress())) {
                        existsInWhiteList = true;
                        break;
                    }
                }
                if (!existsInWhiteList) {
                    foundWhiteListDevices.add(device);
                    if (isAdded()) {
                        updateDeviceDialog();
                    }
                }
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            Log.d("BluetoothScan", "onBatchScanResults回调触发，数量：" + results.size());
            if (!isAdded()) {
                Log.w("BluetoothScan", "Fragment未附加到Activity，忽略批量扫描结果");
                return;
            }
            android.util.Log.d("BluetoothScan", "BLE批量扫描结果: " + results.size() + " 个设备");
            for (ScanResult result : results) {
                if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    continue;
                }
                BluetoothDevice device = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    device = result.getDevice();
                }
                int rssi = 0;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    rssi = result.getRssi();
                }
                
                // ⭐ 修复：将扫描到的设备添加到devices列表
                boolean exists = false;
                for (BluetoothDevice d : devices) {
                    if (d.getAddress().equals(device.getAddress())) {
                        exists = true;
                        break;
                    }
                }
                if (!exists) {
                    devices.add(device);
                    Log.d("BluetoothScan", "批量扫描设备已添加到devices列表: " + device.getAddress());
                }
                
                if (shouldAddDevice(device)) {
                    boolean existsInWhiteList = false;
                    for (BluetoothDevice d : foundWhiteListDevices) {
                        if (d.getAddress().equals(device.getAddress())) {
                            existsInWhiteList = true;
                            break;
                        }
                    }
                    if (!existsInWhiteList) {
                        foundWhiteListDevices.add(device);
                    }
                }
            }
            // 批量扫描完成后更新设备对话框
            if (isAdded() && !foundWhiteListDevices.isEmpty()) {
                updateDeviceDialog();
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            Log.e("BluetoothScan", "onScanFailed回调触发，错误码：" + errorCode);
            if (!isAdded()) {
                Log.w("BluetoothScan", "Fragment未附加到Activity，忽略扫描失败");
                return;
            }
            String errorMessage;
            switch (errorCode) {
                case ScanCallback.SCAN_FAILED_ALREADY_STARTED:
                    errorMessage = "扫描已经启动";
                    break;
                case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
                    errorMessage = "应用注册失败";
                    break;
                case ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED:
                    errorMessage = "设备不支持BLE扫描";
                    break;
                case ScanCallback.SCAN_FAILED_INTERNAL_ERROR:
                    errorMessage = "内部错误";
                    break;
                default:
                    errorMessage = "未知错误: " + errorCode;
            }
            android.util.Log.e("BluetoothScan", "BLE扫描失败: " + errorMessage);
            requireActivity().runOnUiThread(() -> {
                if (isAdded()) {
                    Toast.makeText(requireContext(), "扫描失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    stopScan();
                }
            });
        }
    };

    // UI组件
    private TextView tvBluetoothStatus;
    private Switch swEnableBluetooth;
    private TextView tvNoDevices;
    private Button btnScanDevices;
    private RecyclerView rvHistoryDevices;
    private LinearLayout layoutConnectedDevice;
    private TextView tvConnectedDeviceName;
    private TextView tvConnectedDeviceId;
    private TextView tvConnectedDeviceFirmwareVersion;
    private TextView tvConnectedDeviceFlashVersion;
    private TextView tvConnectedDeviceBatteryLevel;
    private Button btnDisconnect;
    private TextView tvWebsocketResult;
    private Button btnTestAudio;
    private Switch swAutoConnect;
    private Switch swAutoJumpWechat;
    private Switch swUseSpeechV3;
    private Switch swUseSileroVad;
    private Button btnOpenAccessibility;
    
    // TTS相关UI组件
    // private TextView tvTTSStatus;
    // private Button btnConnectTTS;
    // private EditText etTTSInput;
    // private Button btnSendTTS;

    // ADPCM编码解码测试相关UI组件
    // private Button btnEncodeTest;
    // private Button btnDecodeTest;
    // private TextView tvEncodingStatus;
    
    // 编码解码测试相关变量
    // private byte[] lastPcmData = null;
    // private byte[] encodedAdpcmData = null;
    // private AdpcmEncoder testEncoder = new AdpcmEncoder();
    // private AdpcmDecoder testDecoder = new AdpcmDecoder();
    // private AudioTrack testAudioTrack;
    
    // WebSocket相关
    private WebSocket webSocket;
    private boolean isWsConnected = false;
    private int wsRetryCount = 0;
    private static final int MAX_RETRIES = 3;
    private Handler wsRetryHandler = new Handler(Looper.getMainLooper());
    private Runnable wsRetryRunnable;
    
    // 心跳相关
    private Handler heartbeatHandler = new Handler(Looper.getMainLooper());
    private Runnable heartbeatRunnable;
    private static final long HEARTBEAT_INTERVAL = 30000; // 30秒心跳间隔

    // 服务UUID
    private static final Map<String, Map<String, String>> SERVICES = new HashMap<String, Map<String, String>>() {{
        put("fff0", new HashMap<String, String>() {{
            put("uuid", "0000FFF0-0000-1000-8000-00805F9B34FB");
            put("notify", "0000FFF4-0000-1000-8000-00805F9B34FB");
            put("write", "0000FFF2-0000-1000-8000-00805F9B34FB");
        }});
        put("fff1", new HashMap<String, String>() {{
            put("uuid", "0000FFF1-0000-1000-8000-00805F9B34FB");
            put("notify", "0000FFF1-0000-1000-8000-00805F9B34FB");
        }});
        put("d0ff", new HashMap<String, String>() {{
            put("uuid", "0000D0FF-0000-1000-8000-00805F9B34FB");
            put("notify", "0000D002-0000-1000-8000-00805F9B34FB");
            put("write", "0000D001-0000-1000-8000-00805F9B34FB");
        }});
    }};

    // 新增成员变量
    // private BluetoothGattCharacteristic notifyCharacteristic;
    // private BluetoothGattCharacteristic writeCharacteristic;
    // private BluetoothGattCharacteristic fff3WriteCharacteristic;

    // --- BLE音频数据处理相关成员变量 ---
    private static final UUID FFF1_UUID = UUID.fromString("000000f1-0000-1000-8000-00805f9b34fb");
    private static final UUID FFF4_UUID = UUID.fromString("0000fff4-0000-1000-8000-00805f9b34fb");
    private static final UUID FFF3_UUID = UUID.fromString("0000fff3-0000-1000-8000-00805f9b34fb");
    
    // v2配置（原有配置）
    private static final int MIN_START_FRAME_SIZE_V2 = 1280;
    private static final int FRAME_SIZE_V2 = 1280;
    private static final int MIN_CHUNK_SIZE_V2 = 1280;
    private static final int SEND_INTERVAL_V2 = 40; // ms
    
    // v3配置（与HTML页面一致）
    private static final int MIN_START_FRAME_SIZE_V3 = 1600;
    private static final int FRAME_SIZE_V3 = 1600;
    private static final int MIN_CHUNK_SIZE_V3 = 1600;
    private static final int SEND_INTERVAL_V3 = 100; // ms
    
    // 播放超时相关
    private static final long PLAYBACK_TIMEOUT = 1000; // 1秒超时
    private Handler playbackTimeoutHandler = new Handler(Looper.getMainLooper());
    private Runnable playbackTimeoutRunnable;
    private long lastAudioDataTime = 0;
    
    // 动态配置（根据接口版本选择）
    private int getMinStartFrameSize() {
        return useSpeechV3 ? MIN_START_FRAME_SIZE_V3 : MIN_START_FRAME_SIZE_V2;
    }
    
    private int getFrameSize() {
        return useSpeechV3 ? FRAME_SIZE_V3 : FRAME_SIZE_V2;
    }
    
    private int getMinChunkSize() {
        return useSpeechV3 ? MIN_CHUNK_SIZE_V3 : MIN_CHUNK_SIZE_V2;
    }
    
    private int getSendInterval() {
        return useSpeechV3 ? SEND_INTERVAL_V3 : SEND_INTERVAL_V2;
    }
    
    private boolean isStartFrameSent = false;
    private boolean isEndFrameSent = false;
    private long lastSendTime = 0;
    private ByteArrayOutputStream pcmBuffer = new ByteArrayOutputStream();
    private Handler audioHandler = new Handler(Looper.getMainLooper());

    // --- FFF4音频处理相关成员变量 ---
    private ByteArrayOutputStream fff4AdpcmBuffer = new ByteArrayOutputStream();
    private ByteArrayOutputStream fff4PcmBuffer = new ByteArrayOutputStream();
    private long lastFFF4DataTime = 0;
    private static final long FFF4_DATA_TIMEOUT = 1000; // 1秒超时
    private Handler fff4TimeoutHandler = new Handler(Looper.getMainLooper());
    private Runnable fff4TimeoutRunnable;

    // --- FFF3音频输出相关成员变量 ---
    // private BluetoothGattCharacteristic fff3WriteCharacteristic;
    // private static final UUID FFF3_UUID = UUID.fromString("0000fff3-0000-1000-8000-00805f9b34fb");

    private AdpcmDecoder adpcmDecoder = new AdpcmDecoder();
    private static final int PCM_SAMPLE_RATE = 8000;
    private static final int PCM_CHANNELS = 1;
    private static final int PCM_BITS = 16;

    private MediaPlayer mediaPlayer;
    // 新增WAV缓存
    private ByteArrayOutputStream wavPcmBuffer = new ByteArrayOutputStream();

    // 全局设备名称白名单
    private List<String> allowedDeviceNames = new ArrayList<>(Arrays.asList("Hear Me BLE"));
    // 自动连接开关
    private boolean autoConnect = false;
    // 自动跳转微信开关
    private boolean autoJumpWechat = true;
    // 使用speech_v3接口开关
    private boolean useSpeechV3 = false;
    // 历史设备地址
    private static final String PREFS_NAME = "ble_history";
    private static final String KEY_HISTORY_DEVICES = "history_devices";
    private static final String KEY_LAST_DEVICE = "last_device";
    private String lastDeviceAddress = null;

    // 蓝牙状态广播接收器
    private final BroadcastReceiver bluetoothStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // ⭐ 修复：移除自己的蓝牙状态监听，统一使用BleManager
            // String action = intent.getAction();
            // if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            //     final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            //     if (state == BluetoothAdapter.STATE_ON) {
            //         updateBluetoothStatus();
            //     } else if (state == BluetoothAdapter.STATE_OFF) {
            //         updateBluetoothStatus();
            //     }
            // }
            
            // 现在使用BleManager统一管理蓝牙状态，这里不再需要处理
        }
    };

    private HistoryDeviceAdapter historyDeviceAdapter;
    private List<BluetoothDevice> historyDeviceList = new ArrayList<>();

    private static final UUID F2_UUID = UUID.fromString("000000f2-0000-1000-8000-00805f9b34fb");

    private StringBuilder recognitionBuffer = new StringBuilder();
    private static final long RECOGNITION_TIMEOUT = 1000; // 1秒超时
    private Handler recognitionHandler = new Handler(Looper.getMainLooper());
    private Runnable recognitionTimeoutRunnable;

    private FragmentDeviceBinding binding;

    // 宏控制常量
    private static final boolean USE_ASR_CLIENT = true; // 是否使用ASR客户端
    private static final boolean USE_RESAMPLING = true;  // 是否使用重采样（v3模式）
    
    // ASR客户端相关变量（根据宏控制使用）
    private AsrWsClient asrWsClient;
    private boolean isAsrConnected = false;
    
    // TTS管理器
    // private DoubaoTTSManager ttsManager;

    // ADPCM数据写入序号计数器
    private int adpcmWriteCounter = 0;

    // 版本信息更新定时器
    private Handler versionUpdateHandler = new Handler(Looper.getMainLooper());
    private Runnable versionUpdateRunnable;
    private static final long VERSION_UPDATE_INTERVAL = 5000; // 5秒更新一次

    private static final String TAG = "DeviceFragment";
    private static final String WS_PATH = "/ws/speech_v2";
    private static final String WS_PATH_V3 = "/ws/speech_v3";
    
    // 获取服务器地址
    private String getServerUrl() {
        try {
            android.content.SharedPreferences prefs = requireContext().getSharedPreferences("app_config", Context.MODE_PRIVATE);
            return prefs.getString("server_url", "qixin.yeshan.fun");
        } catch (Exception e) {
            Log.e(TAG, "获取服务器地址失败", e);
            return "qixin.yeshan.fun";
        }
    }
    
    // 构建WebSocket URL
    private String buildWebSocketUrl(String path) {
        String serverUrl = getServerUrl();
        return "ws://" + serverUrl + path;
    }

    // 新增：电池电量相关
    private BroadcastReceiver batteryLevelReceiver;

    // 设备类型常量
    private static final int DEVICE_TYPE_DUAL = BluetoothDevice.DEVICE_TYPE_DUAL;
    private static final int DEVICE_TYPE_LE = BluetoothDevice.DEVICE_TYPE_LE;
    private static final int DEVICE_TYPE_CLASSIC = BluetoothDevice.DEVICE_TYPE_CLASSIC;
    
    // 获取设备类型
    private int getDeviceType(BluetoothDevice device) {
        // ⭐ 修复：移除自己的设备类型获取逻辑，统一使用BleManager
        // 现在BleManager统一管理设备类型判断
        return BluetoothDevice.DEVICE_TYPE_LE; // 默认返回LE设备类型
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentDeviceBinding.inflate(inflater, container, false);
        initViews(binding.getRoot());
        setupRecyclerView();
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 初始化BleManager
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            // 初始化BleManager
            bleManager.initialize(requireContext());
            
            // 设置连接监听器
            bleManager.setConnectionListener(new BleManager.BleConnectionListener() {
                @Override
                public void onConnected(BluetoothDevice device) {
                    // ⭐ 修复：添加Fragment状态检查，避免Fragment未附加到Activity时的异常
                    if (!isAdded() || getActivity() == null) {
                        Log.w("DeviceFragment", "Fragment未附加到Activity，跳过连接回调");
                        return;
                    }
                    
                    getActivity().runOnUiThread(() -> {
                        Log.d("DeviceFragment", "BleManager连接成功: " + device.getAddress());
                        
                        // 如果正在扫描，立即停止扫描
                        if (isScanning) {
                            Log.d("DeviceFragment", "设备连接成功，立即停止扫描");
                            stopScan();
                        }
                        
                        updateConnectedDevice(device);
                        
                        // ⭐ 修复：检查设备是否已在历史列表中，避免重新添加已删除的设备
                        boolean deviceExists = false;
                        for (BluetoothDevice historyDevice : historyDeviceList) {
                            if (historyDevice.getAddress().equals(device.getAddress())) {
                                deviceExists = true;
                                break;
                            }
                        }
                        
                        // 只有当设备不在历史列表中时才添加
                        if (!deviceExists) {
                            addDeviceToHistory(device);
                        } else {
                            Log.d("DeviceFragment", "设备已存在于历史列表中，跳过添加: " + device.getAddress());
                        }
                        
                        // 保存设备地址用于自动重连
                        saveLastDeviceAddress(device.getAddress());
                        
                        // 启动版本信息更新定时器
                        startVersionUpdateTimer();
                    });
                }
                
                @Override
                public void onDisconnected(BluetoothDevice device) {
                    // ⭐ 修复：添加Fragment状态检查，避免Fragment未附加到Activity时的异常
                    if (!isAdded() || getActivity() == null) {
                        Log.w("DeviceFragment", "Fragment未附加到Activity，跳过断开连接回调");
                        return;
                    }
                    
                    getActivity().runOnUiThread(() -> {
                        Log.d("DeviceFragment", "BleManager连接断开: " + device.getAddress());
                        clearConnectedDevice();
                    });
                }
            });
            
            // 设置电池电量监听器
            bleManager.setBatteryLevelListener(this);
            
            // ⭐ 新增：设置扫描结果监听器
            bleManager.setScanResultListener(this);
        }
        
        // 初始化视图
        initViews(view);
        
        // 初始化蓝牙
        initBluetooth();
        
        // 设置RecyclerView
        setupRecyclerView();
        
        // 设置监听器
        setupListeners();
        
        // 检查权限
        checkPermissions();
        
        // 加载历史设备
        loadHistoryDevices();
        
        // 注册蓝牙状态广播接收器
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        requireActivity().registerReceiver(bluetoothStateReceiver, filter);
        
        // 注册电池电量广播接收器
        registerBatteryLevelReceiver();
        
        // 初始化ASR客户端
        //initAsrClient();
        
        // 检查是否已经有连接的设备
        checkAndDisplayConnectedDevice();
        
        // ⭐ 修复：添加延迟启动扫描逻辑，确保第一次安装时能正确启动扫描
        // 延迟1秒后检查是否需要启动扫描
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (isAdded() && hasRequiredPermissions()) {
                BleManager delayedBleManager = BleManager.getInstance();
                if (delayedBleManager != null && !delayedBleManager.isConnected() && !isScanning) {
                    Log.d("DeviceFragment", "延迟启动扫描 - 权限已授予且无连接设备");
                    startScan();
                }
            }
        }, 1000);
    }
    
    /**
     * 检查并显示已连接的设备信息
     */
    private void checkAndDisplayConnectedDevice() {
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null && bleManager.isConnected()) {
            BluetoothDevice connectedDevice = bleManager.getConnectedDevice();
            if (connectedDevice != null) {
                Log.d("DeviceFragment", "检测到已连接设备: " + connectedDevice.getAddress());
                
                // 如果正在扫描，立即停止扫描
                if (isScanning) {
                    Log.d("DeviceFragment", "检测到已连接设备，立即停止扫描");
                    stopScan();
                }
                
                updateConnectedDevice(connectedDevice);
                
                // ⭐ 修复：移除addDeviceToHistory调用，避免已删除的设备被重新添加到历史列表
                // 历史设备列表应该只在用户手动连接设备时更新
                // addDeviceToHistory(connectedDevice);
                
                // 启动版本信息更新定时器
                startVersionUpdateTimer();
                
                // ⭐ 修复：移除立即启动电池电量自动更新的代码
                // 电池电量读取现在会在OTA版本读取完成后进行
                // bleManager.startBatteryAutoUpdate();
            }
        } else {
            Log.d("DeviceFragment", "没有检测到已连接的设备");
        }
    }

    private void initBluetooth() {
        // ⭐ 修复：移除自己的蓝牙初始化逻辑，统一使用BleManager
        // BluetoothManager bluetoothManager = (BluetoothManager) requireContext().getSystemService(Context.BLUETOOTH_SERVICE);
        // bluetoothAdapter = bluetoothManager.getAdapter();
        // if (bluetoothAdapter != null) {
        //     bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
        // }
        
        // 使用BleManager进行初始化
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            bleManager.initialize(requireContext());
            // 设置连接监听器
            bleManager.setConnectionListener(new BleManager.BleConnectionListener() {
                @Override
                public void onConnected(BluetoothDevice device) {
                    Log.d("DeviceFragment", "BleManager连接成功: " + device.getAddress());
                    updateConnectedDevice(device);
                }
                
                @Override
                public void onDisconnected(BluetoothDevice device) {
                    Log.d("DeviceFragment", "BleManager连接断开: " + device.getAddress());
                    clearConnectedDevice();
                }
            });
            
            // 设置电池电量监听器
            bleManager.setBatteryLevelListener(this);
            
            // ⭐ 新增：设置扫描结果监听器
            bleManager.setScanResultListener(this);
        }
    }

    private void initViews(View view) {
        tvBluetoothStatus = view.findViewById(R.id.tv_bluetooth_status);
        swEnableBluetooth = view.findViewById(R.id.sw_enable_bluetooth);
        tvNoDevices = view.findViewById(R.id.tv_no_devices);
        btnScanDevices = view.findViewById(R.id.btn_scan_devices);
        rvHistoryDevices = view.findViewById(R.id.rv_history_devices);
        layoutConnectedDevice = view.findViewById(R.id.layout_connected_device);
        tvConnectedDeviceName = view.findViewById(R.id.tv_connected_device_name);
        tvConnectedDeviceId = view.findViewById(R.id.tv_connected_device_id);
        tvConnectedDeviceFirmwareVersion = view.findViewById(R.id.tv_connected_device_firmware_version);
        tvConnectedDeviceFlashVersion = view.findViewById(R.id.tv_connected_device_flash_version);
        tvConnectedDeviceBatteryLevel = view.findViewById(R.id.tv_connected_device_battery_level);
        btnDisconnect = view.findViewById(R.id.btn_disconnect);
        
        // 注释掉不存在的UI组件
        // tvWebsocketResult = view.findViewById(R.id.tv_websocket_result);
        // btnTestAudio = view.findViewById(R.id.btn_test_audio);
        swAutoConnect = view.findViewById(R.id.sw_auto_connect);
        // swAutoJumpWechat = view.findViewById(R.id.sw_auto_jump_wechat);
        // swUseSpeechV3 = view.findViewById(R.id.sw_use_speech_v3);
        swUseSileroVad = view.findViewById(R.id.sw_use_silero_vad);
        // btnOpenAccessibility = view.findViewById(R.id.btn_open_accessibility);
        // btnOpenAccessibility.setText("开启无障碍服务");
        // btnOpenAccessibility.setOnClickListener(v -> {
        //     Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        //     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //     startActivity(intent);
        // });
        
        // 初始化开关状态
        SharedPreferences prefs = requireContext().getSharedPreferences(PREFS_SWITCH, Context.MODE_PRIVATE);
        boolean autoConnectSwitch = prefs.getBoolean(KEY_AUTO_CONNECT_SWITCH, false);
        //boolean autoJumpWechatSwitch = prefs.getBoolean(KEY_AUTO_JUMP_WECHAT_SWITCH, true);
        //boolean useSpeechV3Switch = prefs.getBoolean(KEY_USE_SPEECH_V3_SWITCH, false);
        boolean useSileroVadSwitch = prefs.getBoolean(KEY_USE_SILERO_VAD_SWITCH, true); // 默认使用Silero VAD
        
        swAutoConnect.setChecked(autoConnectSwitch);
        //swAutoJumpWechat.setChecked(autoJumpWechatSwitch);
        //swUseSpeechV3.setChecked(useSpeechV3Switch);
        swUseSileroVad.setChecked(useSileroVadSwitch);
        
            // 初始化VAD管理器
        VadManager vadManager = VadManager.getInstance(requireContext());
        VadDetector.VadType vadType = useSileroVadSwitch ? 
            VadDetector.VadType.SILERO : VadDetector.VadType.WEBRTC;
        vadManager.setVadType(vadType);
        vadManager.initialize();
        
        // 蓝牙开关状态根据系统蓝牙状态设置
        swEnableBluetooth.setChecked(bluetoothAdapter != null && bluetoothAdapter.isEnabled());
        
        // 初始化UI状态
        updateBluetoothStatus();
        // 注释掉WebSocket和TTS状态更新
        // updateWebSocketStatus();
        // updateTTSStatus();
        // 初始化历史设备列表
        setupHistoryDeviceList();
    }

    private void updateBluetoothStatus() {
        // ⭐ 修复：移除自己的蓝牙状态更新逻辑，统一使用BleManager
        // if (bluetoothAdapter != null) {
        //     if (bluetoothAdapter.isEnabled()) {
        //         tvBluetoothStatus.setText("蓝牙状态：已启用");
        //         tvBluetoothStatus.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
        //         swEnableBluetooth.setChecked(true);
        //     } else {
        //         tvBluetoothStatus.setText("蓝牙状态：已禁用");
        //         tvBluetoothStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        //         swEnableBluetooth.setChecked(false);
        //     }
        // } else {
        //     tvBluetoothStatus.setText("蓝牙状态：不可用");
        //     tvBluetoothStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        //     swEnableBluetooth.setChecked(false);
        // }
        
        // 使用BleManager获取蓝牙状态
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            if (bleManager.isConnected()) {
                tvBluetoothStatus.setText("蓝牙状态：已连接");
                tvBluetoothStatus.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
            } else if (bleManager.isScanning()) {
                tvBluetoothStatus.setText("蓝牙状态：扫描中");
                tvBluetoothStatus.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
            } else {
                tvBluetoothStatus.setText("蓝牙状态：未连接");
                tvBluetoothStatus.setTextColor(getResources().getColor(android.R.color.holo_orange_dark));
            }
        } else {
            tvBluetoothStatus.setText("蓝牙状态：未初始化");
            tvBluetoothStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        }
    }

//    private void updateWebSocketStatus() {
//        if (USE_ASR_CLIENT) {
//            // 使用ASR客户端状态显示逻辑
//            if (useSpeechV3) {
//                // v3模式：显示ASR客户端状态
//                if (isAsrConnected) {
//                    tvWebSocketStatus.setText("ASR已连接");
//                    btnConnectWebSocket.setText("断开ASR");
//                } else {
//                    tvWebSocketStatus.setText("ASR未连接");
//                    btnConnectWebSocket.setText("连接ASR");
//                }
//            } else {
//                // v2模式：显示原有WebSocket状态
//                if (isWsConnected) {
//                    tvWebSocketStatus.setText("WebSocket已连接");
//                    btnConnectWebSocket.setText("断开WebSocket");
//                } else {
//                    tvWebSocketStatus.setText("WebSocket未连接");
//                    btnConnectWebSocket.setText("连接WebSocket");
//                }
//            }
//        } else {
//            // 使用老的WebSocket状态显示逻辑
//            if (isWsConnected) {
//                tvWebSocketStatus.setText("WebSocket已连接");
//                btnConnectWebSocket.setText("断开WebSocket");
//            } else {
//                tvWebSocketStatus.setText("WebSocket未连接");
//                btnConnectWebSocket.setText("连接WebSocket");
//            }
//        }
//    }
//
//    private void updateTTSStatus() {
//        if (ttsManager != null && ttsManager.isConnected()) {
//            tvTTSStatus.setText("TTS已连接");
//            btnConnectTTS.setText("断开TTS");
//        } else {
//            tvTTSStatus.setText("TTS未连接");
//            btnConnectTTS.setText("连接TTS");
//        }
//    }

    private void setupRecyclerView() {
        // 初始化deviceAdapter
        deviceAdapter = new DeviceAdapter(this);
        // ⭐ 修复：移除对rvHistoryDevices的错误设置
        // rvHistoryDevices应该在setupHistoryDeviceList中设置
        // rvHistoryDevices.setLayoutManager(new LinearLayoutManager(requireContext()));
        // rvHistoryDevices.setAdapter(deviceAdapter);
    }

    private void setupListeners() {
        swEnableBluetooth.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                }
            } else {
                // ⭐ 修复：删除危险的bluetoothAdapter.disable()调用
                // APP绝不能主动关闭系统蓝牙，这会导致整个蓝牙堆栈崩溃
                Log.w("DeviceFragment", "用户尝试关闭蓝牙，但APP不能主动关闭系统蓝牙");
                Toast.makeText(requireContext(), "请手动在系统设置中关闭蓝牙", Toast.LENGTH_SHORT).show();
                // 恢复开关状态
                buttonView.setChecked(true);
            }
            // 不再保存蓝牙开关状态
        });
        swAutoConnect.setOnCheckedChangeListener((buttonView, isChecked) -> {
            autoConnect = isChecked;
            // 保存自动连接开关状态
            SharedPreferences prefs = requireContext().getSharedPreferences(PREFS_SWITCH, Context.MODE_PRIVATE);
            prefs.edit().putBoolean(KEY_AUTO_CONNECT_SWITCH, isChecked).apply();
        });
        
        // 注释掉不存在的UI组件监听器
        /*
        swAutoJumpWechat.setOnCheckedChangeListener((buttonView, isChecked) -> {
            autoJumpWechat = isChecked;
            // 保存自动跳转微信开关状态
            SharedPreferences prefs = requireContext().getSharedPreferences(PREFS_SWITCH, Context.MODE_PRIVATE);
            prefs.edit().putBoolean(KEY_AUTO_JUMP_WECHAT_SWITCH, isChecked).apply();
        });
        swUseSpeechV3.setOnCheckedChangeListener((buttonView, isChecked) -> {
            useSpeechV3 = isChecked;
            // 保存接口版本开关状态
            SharedPreferences prefs = requireContext().getSharedPreferences(PREFS_SWITCH, Context.MODE_PRIVATE);
            prefs.edit().putBoolean(KEY_USE_SPEECH_V3_SWITCH, isChecked).apply();
        });
        */
        
        swUseSileroVad.setOnCheckedChangeListener((buttonView, isChecked) -> {
            // 设置VAD类型
            VadDetector.VadType vadType = isChecked ? 
                VadDetector.VadType.SILERO : VadDetector.VadType.WEBRTC;
            
            // 设置全局VAD类型
            VadDetector.setVadType(vadType);
            
            // 保存设置
            SharedPreferences prefs = requireContext().getSharedPreferences(PREFS_SWITCH, Context.MODE_PRIVATE);
            prefs.edit().putBoolean(KEY_USE_SILERO_VAD_SWITCH, isChecked).apply();
            
            Log.d("DeviceFragment", "VAD类型切换为: " + vadType.getDisplayName());
        });
        
        btnScanDevices.setOnClickListener(v -> startScan());
        btnDisconnect.setOnClickListener(v -> disconnectDevice());
        //btnConnectWebSocket.setOnClickListener(v -> toggleWebSocket());
        //btnTestAudio.setOnClickListener(v -> testAudioData());
        
        // TTS相关监听器
       // btnConnectTTS.setOnClickListener(v -> toggleTTS());
        //btnSendTTS.setOnClickListener(v -> sendTTSText());
        
        // ADPCM编码解码测试相关监听器
        //btnEncodeTest.setOnClickListener(v -> performEncodeTest());
        //btnDecodeTest.setOnClickListener(v -> performDecodeTest());
    }

    private void checkManifestPermissions() {
        String[] manifestPermissions = {
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        };
        for (String perm : manifestPermissions) {
            try {
                requireContext().getPackageManager().getPermissionInfo(perm, 0);
            } catch (Exception e) {
                Log.e("ManifestCheck", "Manifest缺少权限声明: " + perm);
                Toast.makeText(requireContext(), "Manifest缺少权限声明: " + perm, Toast.LENGTH_LONG).show();
            }
        }
    }

    private void showPermissionDeniedDialog() {
        new AlertDialog.Builder(requireContext())
            .setTitle("权限被拒绝")
            .setMessage("请在系统设置中手动授予蓝牙和定位权限，否则无法使用蓝牙扫描功能。")
            .setPositiveButton("去设置", (dialog, which) -> {
                Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(android.net.Uri.fromParts("package", requireContext().getPackageName(), null));
                startActivity(intent);
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void checkPermissions() {
        // 优先检查定位权限
        if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
            ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            }, REQUEST_PERMISSIONS);
            return;
        }
        // 再检查蓝牙权限
        if (!hasRequiredPermissions()) {
            android.util.Log.d("BluetoothScan", "权限检查失败，开始请求权限");
            requestPermissions();
            return;
        }
        android.util.Log.d("BluetoothScan", "权限检查通过");
        logAllPermissions();
        
        // 检查是否已经有连接的设备，如果有就不启动扫描
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null && bleManager.isConnected()) {
            Log.d("DeviceFragment", "检测到已连接设备，跳过自动扫描");
            return;
        }
        
        // 只有在没有连接设备时才启动扫描
        Log.d("DeviceFragment", "没有检测到已连接设备，开始扫描");
        startScan();
    }

    private boolean hasRequiredPermissions() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            return ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED &&
                   ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED;
        } else {
            return ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED &&
                   ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.BLUETOOTH_ADMIN) == PackageManager.PERMISSION_GRANTED &&
                   ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                   ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        }
    }

    private void enableBluetooth() {
        if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

    private void startScan() {
        if (!hasRequiredPermissions()) {
            requestPermissions();
            return;
        }

        if (!isLocationEnabled()) {
            showLocationSettingsDialog();
            return;
        }
        
        // ⭐ 修复：检查蓝牙是否开启
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Log.d("DeviceFragment", "蓝牙未开启，请求开启蓝牙");
            enableBluetooth();
            return;
        }
        
        // 使用BleManager进行扫描
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            if (bleManager.isScanning()) {
                Log.d("DeviceFragment", "扫描已在进行中");
                return;
            }
            
            // 清空设备列表
            devices.clear();
            foundWhiteListDevices.clear();
            if (deviceAdapter != null) {
                deviceAdapter.notifyDataSetChanged();
            }
            
            // 开始扫描
            bleManager.startScan();
            isScanning = true;
            
            // 更新UI
            btnScanDevices.setText("停止扫描");
            updateNoDevicesVisibility();
            
            // 设置扫描超时
            handler.postDelayed(() -> {
                if (isScanning) {
                    stopScan();
                }
            }, SCAN_PERIOD);
        }
    }

    private boolean isLocationEnabled() {
        LocationManager locationManager = (LocationManager) requireContext().getSystemService(Context.LOCATION_SERVICE);
        return locationManager != null && 
               (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
    }

    private void showLocationSettingsDialog() {
        new AlertDialog.Builder(requireContext())
            .setTitle("需要开启定位服务")
            .setMessage("蓝牙扫描需要开启定位服务，是否前往设置？")
            .setPositiveButton("去设置", (dialog, which) -> {
                Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void requestPermissions() {
        List<String> permissionsToRequest = new ArrayList<>();
        
        // Android 12及以上版本需要的权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_SCAN);
            }
            if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_CONNECT);
            }
        } else {
            // Android 11及以下版本需要的权限
            if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH);
            }
            if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_ADMIN);
            }
            if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
        }

        if (!permissionsToRequest.isEmpty()) {
            android.util.Log.d("BluetoothScan", "请求权限: " + String.join(", ", permissionsToRequest));
            requestPermissions(permissionsToRequest.toArray(new String[0]), REQUEST_PERMISSIONS);
        } else {
            android.util.Log.d("BluetoothScan", "所有权限都已授予");
            // 不自动启动扫描，让用户手动点击扫描按钮
            Log.d("DeviceFragment", "权限已授予，但不自动启动扫描");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSIONS) {
            boolean allGranted = true;
            boolean someDeniedForever = false;
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    // 检查是否永久拒绝
                    if (!shouldShowRequestPermissionRationale(permissions[i])) {
                        someDeniedForever = true;
                    }
                    Log.e("Permissions", "权限被拒绝: " + permissions[i]);
                }
            }
            if (allGranted) {
                Log.d("BluetoothScan", "所有权限都已授予");
                // 权限授予后，先检查是否有已连接设备
                checkAndDisplayConnectedDevice();
                
                // 如果没有已连接设备，启动扫描
                BleManager bleManager = BleManager.getInstance();
                if (bleManager == null || !bleManager.isConnected()) {
                    Log.d("DeviceFragment", "权限授予后，没有检测到已连接设备，开始扫描");
                    startScan();
                }
            } else if (someDeniedForever) {
                showPermissionDeniedDialog();
            } else {
                Log.e("BluetoothScan", "部分权限被拒绝");
                Toast.makeText(requireContext(), "需要相关权限才能使用蓝牙功能", Toast.LENGTH_SHORT).show();
                // 再次请求
                checkPermissions();
            }
        }
    }

    private void stopScan() {
        // ⭐ 修复：移除自己的停止扫描逻辑，统一使用BleManager
        // if (bluetoothLeScanner != null && isScanning) {
        //     try {
        //         if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
        //             return;
        //         }
        //         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        //             bluetoothLeScanner.stopScan(scanCallback);
        //         }
        //     } catch (Exception e) {
        //         android.util.Log.e("BluetoothScan", "停止BLE扫描失败", e);
        //     }
        // }
        
        // 使用BleManager停止扫描
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            bleManager.stopScan();
        }
        
        isScanning = false;
        btnScanDevices.setText("扫描设备");
        updateNoDevicesVisibility();
        
        // ⭐ 修复：扫描结束后显示设备选择弹窗
        // if (!devices.isEmpty()) {
        //     showDeviceSelectDialog();
        // }
    }

    private void updateNoDevicesVisibility() {
        // 已废弃，无需实现
    }

    @Override
    public void onDeviceClick(BluetoothDevice device) {
        Log.d("DeviceClick", "设备点击: " + device.getName() + " (" + device.getAddress() + ")");
        
        // 检查设备类型
        int deviceType = getDeviceType(device);
        Log.d("DeviceClick", "设备类型: " + getDeviceTypeString(deviceType));
        Log.d("DeviceClick", "设备类型值: " + deviceType);
        Log.d("DeviceClick", "DEVICE_TYPE_DUAL值: " + DEVICE_TYPE_DUAL);
        Log.d("DeviceClick", "DEVICE_TYPE_LE值: " + DEVICE_TYPE_LE);
        Log.d("DeviceClick", "DEVICE_TYPE_CLASSIC值: " + DEVICE_TYPE_CLASSIC);
        
        // 使用BleManager进行连接，不再区分设备类型
        Log.d("DeviceClick", "使用BleManager连接设备: " + device.getName());
        
        // 获取BleManager实例
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            // 检查当前连接状态
            boolean isCurrentlyConnected = bleManager.isConnected();
            BluetoothDevice connectedDevice = bleManager.getConnectedDevice();
            Log.d("DeviceClick", "当前连接状态: " + isCurrentlyConnected);
            if (connectedDevice != null) {
                Log.d("DeviceClick", "当前连接设备: " + connectedDevice.getAddress());
            }
            
            // 如果当前已连接，先断开连接
            if (isCurrentlyConnected) {
                Log.d("DeviceClick", "当前已有连接，先断开连接");
                bleManager.disconnect();
                
                // 等待断开完成后再连接新设备
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    connectToDeviceInternal(device);
                }, 1000);
            } else {
                // 直接连接设备
                connectToDeviceInternal(device);
            }
        } else {
            Log.e("DeviceClick", "BleManager实例为空，无法连接设备");
        }
    }
    
    private void connectToDeviceInternal(BluetoothDevice device) {
        Log.d("DeviceClick", "开始连接设备: " + device.getName());
        
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            // 确保BleManager已初始化
            bleManager.initialize(requireContext());
            
            // 重置用户主动断开标记，允许连接
            bleManager.setUserDisconnected(false);
            Log.d("DeviceClick", "手动连接设备，重置用户主动断开标记");
            
            // 确保连接状态正确重置
            if (bleManager.isUserDisconnected()) {
                Log.d("DeviceClick", "检测到用户主动断开标记，强制重置连接状态");
                // 强制重置连接状态
                bleManager.forceReconnect();
            }
            
            // 使用BleManager连接设备
            bleManager.connectToDevice(device);
            
            // ⭐ 修复：检查设备是否已在历史列表中，避免重新添加已删除的设备
            boolean deviceExists = false;
            for (BluetoothDevice historyDevice : historyDeviceList) {
                if (historyDevice.getAddress().equals(device.getAddress())) {
                    deviceExists = true;
                    break;
                }
            }
            
            // 只有当设备不在历史列表中时才添加
            if (!deviceExists) {
                addDeviceToHistory(device);
            } else {
                Log.d("DeviceFragment", "设备已存在于历史列表中，跳过添加: " + device.getAddress());
            }
            
            // 保存设备地址用于自动重连
            saveLastDeviceAddress(device.getAddress());
            
            // 关闭设备选择对话框
            if (deviceDialog != null && deviceDialog.isShowing()) {
                deviceDialog.dismiss();
            }
        } else {
            Log.e("DeviceClick", "BleManager实例为空，无法连接设备");
        }
    }

    private void updateConnectedDevice(BluetoothDevice device) {
        // ⭐ 修复：确保在主线程中更新UI
        requireActivity().runOnUiThread(() -> {
            if (layoutConnectedDevice != null) {
                layoutConnectedDevice.setVisibility(View.VISIBLE);
            }
            
            if (tvConnectedDeviceName != null) {
                String deviceName = device.getName();
                if (deviceName == null || deviceName.isEmpty()) {
                    deviceName = "未知设备";
                }
                tvConnectedDeviceName.setText("设备名称: " + deviceName);
            }
            
            if (tvConnectedDeviceId != null) {
                tvConnectedDeviceId.setText("设备地址: " + device.getAddress());
            }
            
            // 更新版本信息
            updateDeviceVersionInfo();
            
            // 更新电池电量显示
            updateBatteryLevelDisplay();
        });
    }
    
    /**
     * 更新设备版本信息显示
     */
    private void updateDeviceVersionInfo() {
        try {
            // 检查BLE连接状态 - 使用BleManager的连接状态
            BleManager bleManager = BleManager.getInstance();
            if (bleManager == null || !bleManager.isConnected()) {
                Log.w("DeviceFragment", "BLE未连接，跳过版本信息更新");
                tvConnectedDeviceFirmwareVersion.setText("固件版本：未连接");
                tvConnectedDeviceFlashVersion.setText("Flash版本：未连接");
                return;
            }
            
            // 获取OtaManager实例
            com.smart.translator.ota.OtaManager otaManager = com.smart.translator.ota.OtaManager.getInstance();
            if (otaManager == null) {
                Log.w("DeviceFragment", "OtaManager为空，跳过版本信息更新");
                tvConnectedDeviceFirmwareVersion.setText("固件版本：获取失败");
                tvConnectedDeviceFlashVersion.setText("Flash版本：获取失败");
                return;
            }
            
            // 检查OtaManager是否已初始化
            if (!otaManager.isInitialized()) {
                Log.d("DeviceFragment", "OtaManager未初始化，进行初始化");
                otaManager.init(requireContext(), bleManager);
            }
            
            // 获取版本信息
            String firmwareVersion = otaManager.getCm3Version();
            String flashVersion = otaManager.getExternalFlashVersion();
            
            Log.d("DeviceFragment", "版本信息获取 - 固件版本: " + firmwareVersion + ", Flash版本: " + flashVersion);
            Log.d("DeviceFragment", "版本信息详情 - 固件版本长度: " + (firmwareVersion != null ? firmwareVersion.length() : "null") + 
                    ", Flash版本长度: " + (flashVersion != null ? flashVersion.length() : "null"));
            Log.d("DeviceFragment", "版本信息详情 - 固件版本是否为空: " + (firmwareVersion != null ? firmwareVersion.isEmpty() : "null") + 
                    ", Flash版本是否为空: " + (flashVersion != null ? flashVersion.isEmpty() : "null"));
            Log.d("DeviceFragment", "版本信息详情 - 固件版本是否等于0.0.0: " + (firmwareVersion != null ? firmwareVersion.equals("0.0.0") : "null") + 
                    ", Flash版本是否等于0.0.0: " + (flashVersion != null ? flashVersion.equals("0.0.0") : "null"));
            
            // 更新UI - 修复判断逻辑
            if (firmwareVersion != null && !firmwareVersion.equals("0.0.0") && !firmwareVersion.isEmpty()) {
                tvConnectedDeviceFirmwareVersion.setText("固件版本：" + firmwareVersion);
                Log.d("DeviceFragment", "固件版本已更新: " + firmwareVersion);
            } else {
                tvConnectedDeviceFirmwareVersion.setText("固件版本：获取中...");
                Log.d("DeviceFragment", "固件版本未获取到，尝试重新获取");
                // 如果版本信息未获取到，尝试重新获取
                otaManager.requestDeviceVersion();
            }
            
            if (flashVersion != null && !flashVersion.equals("0.0.0") && !flashVersion.isEmpty()) {
                tvConnectedDeviceFlashVersion.setText("Flash版本：" + flashVersion);
                Log.d("DeviceFragment", "Flash版本已更新: " + flashVersion);
            } else {
                tvConnectedDeviceFlashVersion.setText("Flash版本：获取中...");
                Log.d("DeviceFragment", "Flash版本未获取到，尝试重新获取");
                // 如果版本信息未获取到，尝试重新获取
                otaManager.requestDeviceVersion();
            }
            
            // 如果版本信息都获取到了，停止定时更新
            if ((firmwareVersion != null && !firmwareVersion.equals("0.0.0") && !firmwareVersion.isEmpty()) && 
                (flashVersion != null && !flashVersion.equals("0.0.0") && !flashVersion.isEmpty())) {
                stopVersionUpdateTimer();
                Log.d("DeviceFragment", "版本信息获取完成，停止定时更新");
            } else {
                // 如果版本信息未完全获取到，启动定时更新
                startVersionUpdateTimer();
                Log.d("DeviceFragment", "版本信息未完全获取到，启动定时更新");
            }
            
        } catch (Exception e) {
            Log.e("DeviceFragment", "更新版本信息失败", e);
            tvConnectedDeviceFirmwareVersion.setText("固件版本：获取失败");
            tvConnectedDeviceFlashVersion.setText("Flash版本：获取失败");
            startVersionUpdateTimer(); // 启动定时更新，尝试重新获取
        }
    }
    
    /**
     * 启动版本信息更新定时器
     */
    private void startVersionUpdateTimer() {
        if (versionUpdateRunnable != null) {
            versionUpdateHandler.removeCallbacks(versionUpdateRunnable);
        }
        versionUpdateRunnable = new Runnable() {
            @Override
            public void run() {
                if (isAdded() && layoutConnectedDevice.getVisibility() == View.VISIBLE) {
                    updateDeviceVersionInfo();
                    // 更新电池电量显示
                    updateBatteryLevelDisplay();
                    // 继续定时器
                    //versionUpdateHandler.postDelayed(this, VERSION_UPDATE_INTERVAL);
                }
            }
        };
        versionUpdateHandler.postDelayed(versionUpdateRunnable, VERSION_UPDATE_INTERVAL);
        Log.d("DeviceFragment", "版本信息和电池电量更新定时器已启动");
    }
    
    /**
     * 停止版本信息更新定时器
     */
    private void stopVersionUpdateTimer() {
        if (versionUpdateRunnable != null) {
            versionUpdateHandler.removeCallbacks(versionUpdateRunnable);
            versionUpdateRunnable = null;
            Log.d("DeviceFragment", "停止版本信息更新定时器");
        }
    }

    private void clearConnectedDevice() {
        Log.d("DeviceFragment", "清除连接的设备信息");
        
        // 隐藏连接设备布局
        layoutConnectedDevice.setVisibility(View.GONE);
        
        // 清除设备信息
        tvConnectedDeviceName.setText("设备名称：未连接");
        tvConnectedDeviceId.setText("设备ID：未连接");
        tvConnectedDeviceFirmwareVersion.setText("固件版本：未连接");
        tvConnectedDeviceFlashVersion.setText("Flash版本：未连接");
        tvConnectedDeviceBatteryLevel.setText("电池电量：未连接");
        
        // 停止版本信息更新定时器
        stopVersionUpdateTimer();
        
        // 停止电池电量自动更新
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            bleManager.stopBatteryAutoUpdate();
        }
        
        Log.d("DeviceFragment", "连接的设备信息已清除");
    }

    private void disconnectDevice() {
        // ⭐ 修复：移除自己的断开连接逻辑，统一使用BleManager
        // if (bluetoothGatt != null) {
        //     bluetoothGatt.disconnect();
        //     bluetoothGatt.close();
        //     bluetoothGatt = null;
        // }
        
        // 使用BleManager断开连接
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            bleManager.setUserDisconnected(true);
            bleManager.disconnect();
        }
        
        // 清空连接设备显示
        clearConnectedDevice();
    }

    private void toggleWebSocket() {
        if (USE_ASR_CLIENT) {
            // 使用ASR客户端逻辑
            if (useSpeechV3) {
                // v3模式：切换ASR客户端连接状态
                if (isAsrConnected) {
                    closeWebSocket();
                } else {
                    Log.d("BLE", "v3开关已开启，手动连接ASR WebSocket");
                    initAsrClient();
                }
            } else {
                // v2模式：切换原有WebSocket连接状态
                if (isWsConnected) {
                    closeWebSocket();
                } else {
                    Log.d("BLE", "v3开关未开启，连接原有WebSocket");
                    initWebSocket();
                }
            }
        } else {
            // 使用老的WebSocket切换逻辑
            if (isWsConnected) {
                closeWebSocket();
            } else {
                // 根据v3开关状态选择连接不同的WebSocket
                if (useSpeechV3) {
                    Log.d("BLE", "v3开关已开启，连接v3 WebSocket");
                    initWebSocket();
                } else {
                    Log.d("BLE", "v3开关未开启，连接v2 WebSocket");
                    initWebSocket();
                }
            }
        }
    }

    private void initWebSocket() {
        if (webSocket != null) {
            webSocket.close(1000, "重新初始化");
        }
        
        String url = buildWebSocketUrl(useSpeechV3 ? WS_PATH_V3 : WS_PATH);
        Log.d("BLE", "初始化WebSocket，URL: " + url);
        
        Request request = new Request.Builder()
                .url(url)
                .build();
        
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        
        webSocket = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                Log.d("BLE", "WebSocket连接成功");
                isWsConnected = true;
                wsRetryCount = 0;
                
                // 检查Fragment是否还附加到Activity
                if (isAdded()) {
                    requireActivity().runOnUiThread(() -> {
                        //updateWebSocketStatus();
                    });
                }
            }
            
            @Override
            public void onMessage(WebSocket webSocket, String text) {
                Log.d("BLE", "WebSocket收到消息: " + text);
                
                // 检查Fragment是否还附加到Activity
                if (isAdded()) {
                    onWebSocketMessage(text);
                }
            }
            
            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                Log.d("BLE", "WebSocket连接关闭，代码: " + code + ", 原因: " + reason);
                isWsConnected = false;
                
                // 检查Fragment是否还附加到Activity
                if (isAdded()) {
                    requireActivity().runOnUiThread(() -> {
                        //updateWebSocketStatus();
                    });
                }
            }
            
            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                Log.e("BLE", "WebSocket连接失败", t);
                isWsConnected = false;
                
                // 检查Fragment是否还附加到Activity
                if (isAdded()) {
                    requireActivity().runOnUiThread(() -> {
                        //updateWebSocketStatus();
                    });
                }
            }
        });
    }
    
    private void closeWebSocket() {
        if (USE_ASR_CLIENT) {
            // 使用ASR客户端关闭逻辑
            if (useSpeechV3) {
                // v3模式：关闭ASR客户端
                if (asrWsClient != null) {
                    asrWsClient.close();
                    asrWsClient = null;
                    isAsrConnected = false;
                    Log.d("BLE", "ASR客户端已关闭");
                }
            } else {
                // v2模式：关闭原有WebSocket
                if (webSocket != null) {
                    webSocket.close(1000, null);
                    webSocket = null;
                }
                isWsConnected = false;
                // 停止心跳机制
                stopHeartbeat();
            }
        } else {
            // 使用老的WebSocket关闭逻辑
            if (webSocket != null) {
                webSocket.close(1000, null);
                webSocket = null;
            }
            isWsConnected = false;
            // 停止心跳机制
            stopHeartbeat();
        }
        
        // 更新UI状态
        //updateWebSocketStatus();
    }

    private void testAudioData() {
        // 这里可以添加测试音频数据的逻辑
        Toast.makeText(requireContext(), "测试音频数据", Toast.LENGTH_SHORT).show();
    }
    
    // TTS相关方法
//    private void toggleTTS() {
//        if (ttsManager == null) {
//            // 初始化TTS管理器
//            ttsManager = new DoubaoTTSManager();
//            ttsManager.setStateListener(new DoubaoTTSManager.TTSStateListener() {
//                @Override
//                public void onConnected() {
//                    requireActivity().runOnUiThread(() -> {
//                        updateTTSStatus();
//                        Toast.makeText(requireContext(), "TTS连接成功", Toast.LENGTH_SHORT).show();
//                    });
//                }
//
//                @Override
//                public void onDisconnected() {
//                    requireActivity().runOnUiThread(() -> {
//                        updateTTSStatus();
//                        Toast.makeText(requireContext(), "TTS连接断开", Toast.LENGTH_SHORT).show();
//                    });
//                }
//
//                @Override
//                public void onError(String error) {
//                    requireActivity().runOnUiThread(() -> {
//                        updateTTSStatus();
//                        Toast.makeText(requireContext(), "TTS错误: " + error, Toast.LENGTH_SHORT).show();
//                    });
//                }
//
//                @Override
//                public void onSynthesisComplete() {
//                    requireActivity().runOnUiThread(() -> {
//                        Toast.makeText(requireContext(), "TTS合成完成", Toast.LENGTH_SHORT).show();
//                        // 启用编码测试按钮
//                        btnEncodeTest.setEnabled(true);
//                        tvEncodingStatus.setText("TTS播放完成，可以点击编码测试按钮");
//                    });
//                }
//            });
//
//            // 设置BLE写入回调
//            ttsManager.setBleWriteCallback(new DoubaoTTSManager.BleWriteCallback() {
//                @Override
//                public void onWriteAdpcmData(byte[] adpcmData) {
//                    writeAdpcmDataToFFF3(adpcmData);
//                }
//            });
//
//            // 设置PCM数据回调
//            ttsManager.setPcmDataCallback(new DoubaoTTSManager.PcmDataCallback() {
//                @Override
//                public void onPcmDataReceived(byte[] pcmData) {
//                    // 保存PCM数据用于编码测试
//                    if (lastPcmData == null) {
//                        lastPcmData = pcmData;
//                    } else {
//                        // 如果已有数据，则追加
//                        byte[] combined = new byte[lastPcmData.length + pcmData.length];
//                        System.arraycopy(lastPcmData, 0, combined, 0, lastPcmData.length);
//                        System.arraycopy(pcmData, 0, combined, lastPcmData.length, pcmData.length);
//                        lastPcmData = combined;
//                    }
//                    Log.d("TTS", "保存PCM数据用于编码测试: " + pcmData.length + " 字节，总计: " + lastPcmData.length + " 字节");
//                }
//            });
//
//            ttsManager.initTTS();
//        }
//
//        if (ttsManager.isConnected()) {
//            // 断开TTS连接
//            ttsManager.disconnect();
//        } else {
//            // 连接TTS
//            ttsManager.connect();
//        }
//    }
//
//    private void sendTTSText() {
//        if (ttsManager == null || !ttsManager.isConnected()) {
//            Toast.makeText(requireContext(), "TTS未连接，请先连接TTS", Toast.LENGTH_SHORT).show();
//            return;
//        }
//
//        String text = etTTSInput.getText().toString().trim();
//        if (text.isEmpty()) {
//            Toast.makeText(requireContext(), "请输入要合成的文本", Toast.LENGTH_SHORT).show();
//            return;
//        }
//
//        // 清空ADPCM数据文件，开始新的记录
//        clearAdpcmDataFile();
//
//        // 清空实时编码ADPCM文件，开始新的记录
//        clearRealtimeAdpcmFile();
//
//        // 清空BLE发送ADPCM文件，开始新的记录
//        clearBleSentAdpcmFile();
//
//        // 重置编码解码测试状态
//        lastPcmData = null;
//        encodedAdpcmData = null;
//        btnEncodeTest.setEnabled(false);
//        btnDecodeTest.setEnabled(false);
//        tvEncodingStatus.setText("正在播放TTS音频...");
//
//        // 发送文本进行TTS合成
//        ttsManager.synthesizeText(text);
//        Log.d("TTS", "发送文本进行TTS合成: " + text);
//    }

    /**
     * 将ADPCM数据写入FFF3特征
     * @param adpcmData ADPCM编码的音频数据
     */
    private void writeAdpcmDataToFFF3(byte[] adpcmData) {
        Log.d("BLE", "准备写入FFF3 ADPCM数据，长度: " + adpcmData.length);
        
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null && bleManager.isConnected()) {
            boolean success = bleManager.writeFff3Data(adpcmData);
            if (success) {
                Log.d("BLE", "FFF3 ADPCM数据写入请求成功");
                adpcmWriteCounter++;
                Log.d("BLE", "FFF3写入计数器: " + adpcmWriteCounter);
            } else {
                Log.w("BLE", "FFF3 ADPCM数据写入请求失败");
            }
        } else {
            Log.w("BLE", "BleManager不可用或设备未连接，无法写入FFF3数据");
        }
    }
    
    /**
     * 将ADPCM数据保存到本地txt文件
     * @param adpcmData ADPCM编码的音频数据
     */
    private void saveAdpcmDataToFile(byte[] adpcmData) {
        try {
            // 获取外部存储目录
            File externalDir = requireContext().getExternalFilesDir(null);
            if (externalDir == null) {
                Log.e("BLE", "无法获取外部存储目录");
                return;
            }
            
            // 创建ADPCM数据文件
            File adpcmFile = new File(externalDir, "fff3_adpcm_data.txt");
            
            // 将字节数组转换为十六进制字符串
            String hexString = bytesToHex(adpcmData);
            
            // 记录写入前的文件大小
            long fileSizeBefore = adpcmFile.length();
            
            // 追加写入文件（使用追加模式）
            java.io.FileWriter fileWriter = new java.io.FileWriter(adpcmFile, true);
            java.io.BufferedWriter bufferedWriter = new java.io.BufferedWriter(fileWriter);
            
            // 写入数据
            bufferedWriter.write(hexString);
            bufferedWriter.newLine();
            
            // 强制刷新缓冲区
            bufferedWriter.flush();
            fileWriter.flush();
            
            // 关闭文件
            bufferedWriter.close();
            fileWriter.close();
            
            // 记录写入后的文件大小
            long fileSizeAfter = adpcmFile.length();
            
            // 显示文件路径（只在第一次写入时显示）
            if (fileSizeBefore == 0) { // 第一次写入
                Log.d("BLE", "ADPCM数据已保存到文件: " + adpcmFile.getAbsolutePath());
                Log.d("BLE", "文件路径: " + adpcmFile.getAbsolutePath());
            }
            
            // 记录数据统计信息
            Log.d("BLE", "本次发送数据长度: " + adpcmData.length + " 字节");
            Log.d("BLE", "写入前文件大小: " + fileSizeBefore + " 字节");
            Log.d("BLE", "写入后文件大小: " + fileSizeAfter + " 字节");
            Log.d("BLE", "本次写入增加: " + (fileSizeAfter - fileSizeBefore) + " 字节");
            Log.d("BLE", "保存的十六进制数据: " + hexString);
            
        } catch (Exception e) {
            Log.e("BLE", "保存ADPCM数据到文件失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 清空ADPCM数据文件
     */
    private void clearAdpcmDataFile() {
        try {
            // 获取外部存储目录
            File externalDir = requireContext().getExternalFilesDir(null);
            if (externalDir == null) {
                Log.e("BLE", "无法获取外部存储目录");
                return;
            }
            
            // 创建ADPCM数据文件
            File adpcmFile = new File(externalDir, "fff3_adpcm_data.txt");
            
            // 记录清空前的文件大小
            long fileSizeBefore = adpcmFile.length();
            
            // 清空文件内容
            java.io.FileWriter fileWriter = new java.io.FileWriter(adpcmFile, false);
            fileWriter.write(""); // 写入空字符串
            fileWriter.flush(); // 强制刷新
            fileWriter.close();
            
            // 记录清空后的文件大小
            long fileSizeAfter = adpcmFile.length();
            
            Log.d("BLE", "已清空ADPCM数据文件: " + adpcmFile.getAbsolutePath());
            Log.d("BLE", "清空前文件大小: " + fileSizeBefore + " 字节");
            Log.d("BLE", "清空后文件大小: " + fileSizeAfter + " 字节");
            Log.d("BLE", "清空操作成功，文件已重置");
            
        } catch (Exception e) {
            Log.e("BLE", "清空ADPCM数据文件失败: " + e.getMessage(), e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // ⭐ 修复：移除自己的蓝牙状态监听器注销，统一使用BleManager
        // requireContext().unregisterReceiver(bluetoothStateReceiver);
        
        // 停止版本更新定时器
        stopVersionUpdateTimer();
        
        // 停止心跳
        stopHeartbeat();
        
        // 关闭WebSocket
        closeWebSocket();
        
        // 清理ASR客户端
        if (asrWsClient != null) {
            asrWsClient.close();
            asrWsClient = null;
        }
        
        // 清理TTS管理器
        // ⭐ 修复：移除ttsManager引用，现在由AudioProcessor统一管理
        // if (ttsManager != null) {
        //     ttsManager.disconnect();
        //     ttsManager = null;
        // }
        
        // 清理音频处理器
        // ⭐ 修复：移除audioProcessor引用，现在由BleManager统一管理
        // if (audioProcessor != null) {
        //     audioProcessor.cleanup();
        //     audioProcessor = null;
        // }
        
        // 清理媒体播放器
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        
        // 清理音频轨道
        // ⭐ 修复：移除testAudioTrack引用，现在由AudioProcessor统一管理
        // if (testAudioTrack != null) {
        //     testAudioTrack.release();
        //     testAudioTrack = null;
        // }
        
        // 清理VAD检测器
        // ⭐ 修复：移除vadDetector引用，现在由AudioProcessor统一管理
        // if (vadDetector != null) {
        //     vadDetector.cleanup();
        //     vadDetector = null;
        // }
        
        // 清理各种超时处理器
        if (playbackTimeoutHandler != null) {
            playbackTimeoutHandler.removeCallbacksAndMessages(null);
        }
        if (fff4TimeoutHandler != null) {
            fff4TimeoutHandler.removeCallbacksAndMessages(null);
        }
        if (recognitionHandler != null) {
            recognitionHandler.removeCallbacksAndMessages(null);
        }
        if (versionUpdateHandler != null) {
            versionUpdateHandler.removeCallbacksAndMessages(null);
        }
        if (wsRetryHandler != null) {
            wsRetryHandler.removeCallbacksAndMessages(null);
        }
        if (heartbeatHandler != null) {
            heartbeatHandler.removeCallbacksAndMessages(null);
        }
        if (audioHandler != null) {
            audioHandler.removeCallbacksAndMessages(null);
        }
        // ⭐ 修复：移除不存在的Handler引用
        // if (vadMessageHandler != null) {
        //     vadMessageHandler.removeCallbacksAndMessages(null);
        // }
        // if (asrConnectTimeoutHandler != null) {
        //     asrConnectTimeoutHandler.removeCallbacksAndMessages(null);
        // }
        // if (audioDataTimeoutHandler != null) {
        //     audioDataTimeoutHandler.removeCallbacksAndMessages(null);
        // }
        // if (ttsTimeoutHandler != null) {
        //     ttsTimeoutHandler.removeCallbacksAndMessages(null);
        // }
        
        // 清理缓冲区
        if (pcmBuffer != null) {
            try {
                pcmBuffer.close();
            } catch (IOException e) {
                Log.e("DeviceFragment", "关闭PCM缓冲区失败", e);
            }
            pcmBuffer = null;
        }
        if (wavPcmBuffer != null) {
            try {
                wavPcmBuffer.close();
            } catch (IOException e) {
                Log.e("DeviceFragment", "关闭WAV PCM缓冲区失败", e);
            }
            wavPcmBuffer = null;
        }
        if (fff4AdpcmBuffer != null) {
            try {
                fff4AdpcmBuffer.close();
            } catch (IOException e) {
                Log.e("DeviceFragment", "关闭FFF4 ADPCM缓冲区失败", e);
            }
            fff4AdpcmBuffer = null;
        }
        if (fff4PcmBuffer != null) {
            try {
                fff4PcmBuffer.close();
            } catch (IOException e) {
                Log.e("DeviceFragment", "关闭FFF4 PCM缓冲区失败", e);
            }
            fff4PcmBuffer = null;
        }
        
        // 清理识别缓冲区
        if (recognitionBuffer != null) {
            recognitionBuffer.setLength(0);
            recognitionBuffer = null;
        }
        
        // 清理历史设备列表
        if (historyDeviceList != null) {
            historyDeviceList.clear();
        }
        
        // 清理设备列表
        if (devices != null) {
            devices.clear();
        }
        if (rssiValues != null) {
            rssiValues.clear();
        }
        
        // 清理白名单设备列表
        if (foundWhiteListDevices != null) {
            foundWhiteListDevices.clear();
        }
        
        // 清理对话框
        if (deviceDialog != null) {
            deviceDialog.dismiss();
            deviceDialog = null;
        }
        
        // 清理适配器
        if (deviceAdapter != null) {
            deviceAdapter = null;
        }
        if (historyDeviceAdapter != null) {
            historyDeviceAdapter = null;
        }
        if (deviceAdapterDialog != null) {
            deviceAdapterDialog = null;
        }
        
        // 清理绑定
        if (binding != null) {
            binding = null;
        }
        
        Log.d("DeviceFragment", "资源清理完成");
    }

    @Override
    public void onResume() {
        super.onResume();
        // ⭐ 修复：移除自己的蓝牙状态监听器注册，统一使用BleManager
        // requireContext().registerReceiver(bluetoothStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
        
        // 更新蓝牙状态显示
        updateBluetoothStatus();
        
        // 检查并显示已连接设备
        checkAndDisplayConnectedDevice();
    }

    @Override
    public void onPause() {
        super.onPause();
        // ⭐ 修复：移除自己的蓝牙状态监听器注销，统一使用BleManager
        // requireContext().unregisterReceiver(bluetoothStateReceiver);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            updateBluetoothStatus();
            
            // ⭐ 修复：蓝牙开启后，如果权限已授予且无连接设备，启动扫描
            if (resultCode == Activity.RESULT_OK && hasRequiredPermissions()) {
                BleManager bleManager = BleManager.getInstance();
                if (bleManager != null && !bleManager.isConnected() && !isScanning) {
                    Log.d("DeviceFragment", "蓝牙开启后，权限已授予且无连接设备，启动扫描");
                    startScan();
                }
            }
        }
    }

    private void logAllPermissions() {
        String[] perms = {
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        };
        for (String perm : perms) {
            int state = ActivityCompat.checkSelfPermission(requireContext(), perm);
            Log.d("PermissionState", perm + ": " + (state == PackageManager.PERMISSION_GRANTED ? "GRANTED" : "DENIED"));
        }
    }

    private boolean shouldAddDevice(BluetoothDevice device) {
        if (device == null) return false;
        String name = device.getName();
        if (name == null) name = "";
        // 只显示白名单内设备
        if (!allowedDeviceNames.isEmpty() && !allowedDeviceNames.contains(name)) return false;
        return true;
    }

    // 辅助方法：查找并设置特征
    private void findAndSetCharacteristics(BluetoothGatt gatt) {
        // ⭐ 修复：移除自己的特征查找逻辑，统一使用BleManager
        // 现在BleManager统一管理特征查找和通知启用
        Log.d("DeviceFragment", "特征查找和通知启用由BleManager统一管理");
    }
    
    private void enableNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        // ⭐ 修复：移除自己的通知启用逻辑，统一使用BleManager
        // 现在BleManager统一管理通知启用
        Log.d("DeviceFragment", "通知启用由BleManager统一管理");
    }

    // 提供写入数据方法
    private void writeDataToDevice(byte[] data) {
        // ⭐ 修复：移除自己的数据写入逻辑，统一使用BleManager
        // if (bluetoothGatt != null && writeCharacteristic != null) {
        //     writeCharacteristic.setValue(data);
        //     boolean result = bluetoothGatt.writeCharacteristic(writeCharacteristic);
        //     Log.d("BLE", "数据写入结果: " + result);
        // }
        
        // 使用BleManager写入数据
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            boolean result = bleManager.writeData(data);
            Log.d("DeviceFragment", "BleManager数据写入结果: " + result);
        }
    }

    // 辅助方法：字节转16进制字符串
    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString();
    }

    // --- BLE音频数据分帧处理 ---
    private void handleBluetoothData(byte[] data) {
        // ⭐ 修复：移除自己的蓝牙数据处理逻辑，统一使用BleManager
        // 现在BleManager统一管理蓝牙数据处理
        Log.d("DeviceFragment", "蓝牙数据处理由BleManager统一管理");
    }

    private byte[] shortArrayToByteArray(short[] arr) {
        byte[] out = new byte[arr.length * 2];
        for (int i = 0; i < arr.length; i++) {
            out[i * 2] = (byte) (arr[i] & 0xFF);
            out[i * 2 + 1] = (byte) ((arr[i] >> 8) & 0xFF);
        }
        return out;
    }

    // 修改savePcmAsWav方法，接收参数
    private void savePcmAsWav(byte[] pcm) {
        savePcmAsWav(pcm, false);
    }
    
    // 修改savePcmAsWav方法，支持超时播放标识
    private void savePcmAsWav(byte[] pcm, boolean isTimeoutPlayback) {
        try {
            byte[] wav = WavUtil.pcmToWav(pcm, PCM_SAMPLE_RATE, PCM_CHANNELS, PCM_BITS);
            // 保存到私有目录
            String fileName = isTimeoutPlayback ? "ble_record_timeout.wav" : "ble_record.wav";
            File wavFile = new File(requireContext().getExternalFilesDir(null), fileName);
            FileOutputStream fos = new FileOutputStream(wavFile);
            fos.write(wav);
            fos.close();
            Log.d("BLE", "WAV文件已保存: " + wavFile.getAbsolutePath() + (isTimeoutPlayback ? " (超时播放)" : ""));
            // 保存后自动播放
            playWavFile(wavFile);
        } catch (Exception e) {
            Log.e("BLE", "保存WAV异常", e);
        }
    }

    private void playWavFile(File wavFile) {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.release();
            }
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(wavFile.getAbsolutePath());
            mediaPlayer.prepare();
            mediaPlayer.start();
            Log.d("BLE", "开始播放WAV文件");
        } catch (Exception e) {
            Log.e("BLE", "播放WAV异常", e);
        }
    }

    // --- 处理首帧 ---
    private void processStartFrame(byte[] data) {
        // TODO: ADPCM解码，PCM数据合并到缓冲区
        appendPcmData(data);
        checkAndSendData();
    }

    // --- 处理中间帧 ---
    private void processMiddleFrame(byte[] data) {
        // TODO: ADPCM解码，PCM数据合并到缓冲区
        appendPcmData(data);
        checkAndSendData();
    }

    // --- PCM数据合并到缓冲区 ---
    private void appendPcmData(byte[] pcm) {
        try {
            pcmBuffer.write(pcm);
        } catch (Exception e) {
            Log.e("BLE", "PCM数据写入缓冲区异常", e);
        }
    }

    // --- 检查并发送数据 ---
    private void checkAndSendData() {
        int len = pcmBuffer.size();
        long now = System.currentTimeMillis();
        
        // 计算当前累积的样本数（每个样本2字节）
        int sampleCount = len / 2;
        
        if (!isStartFrameSent) {
            // 起始帧需要累积足够的样本数
            int requiredSamples = getMinStartFrameSize() / 2;
            if (sampleCount >= requiredSamples) {
                Log.d("BLE", "缓冲区样本数达到起始帧要求，开始发送。当前样本数: " + sampleCount + ", 需要样本数: " + requiredSamples);
                sendBufferedData(false);
            } else {
                Log.d("BLE", "等待更多数据，当前样本数: " + sampleCount + ", 需要样本数: " + requiredSamples);
            }
            return;
        }
        
        // 中间帧需要累积足够的样本数且时间间隔足够
        int requiredSamples = getFrameSize() / 2;
        if (sampleCount >= requiredSamples && now - lastSendTime >= getSendInterval()) {
            Log.d("BLE", "发送中间帧数据。当前样本数: " + sampleCount + ", 需要样本数: " + requiredSamples + ", 时间间隔: " + (now - lastSendTime) + "ms");
            sendBufferedData(false);
        } else {
            if (sampleCount < requiredSamples) {
                Log.d("BLE", "样本数不足，等待更多数据。当前样本数: " + sampleCount + ", 需要样本数: " + requiredSamples);
            } else {
                Log.d("BLE", "时间间隔不足，等待发送。当前间隔: " + (now - lastSendTime) + "ms, 需要间隔: " + getSendInterval() + "ms");
            }
        }
    }

    // --- 发送缓冲数据到WebSocket ---
    private void sendBufferedData(boolean isEndFrame) {
        if (webSocket == null || !isWsConnected) {
            Log.w("BLE", "WebSocket未连接，数据保留在缓冲区");
            return;
        }
        try {
            if (!isStartFrameSent) {
                // 发送起始帧
                byte[] all = pcmBuffer.toByteArray();
                int sendLen = Math.min(all.length, getMinStartFrameSize());
                byte[] startFrame = Arrays.copyOfRange(all, 0, sendLen);
                String base64 = Base64.encodeToString(startFrame, Base64.NO_WRAP);
                JSONObject json = new JSONObject();
                json.put("type", "audio");
                json.put("frame_type", 0);
                json.put("data", base64);
                String message = json.toString();
                Log.d("BLE", "发送起始帧，长度: " + sendLen + ", 消息长度: " + message.length());
                Log.d("BLE", "当前配置 - 起始帧大小: " + getMinStartFrameSize() + 
                             ", 帧大小: " + getFrameSize() + 
                             ", 发送间隔: " + getSendInterval() + "ms");
                Log.d("BLE", "Base64数据长度: " + base64.length());
                webSocket.send(message);
                isStartFrameSent = true;
                lastSendTime = System.currentTimeMillis();
                // 移除已发送数据
                pcmBuffer = new ByteArrayOutputStream();
                pcmBuffer.write(all, sendLen, all.length - sendLen);
                Log.d("BLE", "起始帧发送成功，剩余数据长度: " + (all.length - sendLen));
                // 继续发送剩余数据
                checkAndSendData();
                return;
            }
            // 发送中间帧或结束帧
            byte[] all = pcmBuffer.toByteArray();
            int sendLen = Math.min(all.length, getFrameSize());
            if (isEndFrame && sendLen == 0) {
                // 发送空结束帧
                JSONObject json = new JSONObject();
                json.put("type", "audio");
                json.put("frame_type", 2);
                json.put("data", "");
                String message = json.toString();
                Log.d("BLE", "发送空结束帧");
                webSocket.send(message);
                isEndFrameSent = true;
                lastSendTime = System.currentTimeMillis();
                return;
            }
            if (sendLen < getMinChunkSize() && !isEndFrame) {
                Log.d("BLE", "数据量不足，等待更多数据");
                return;
            }
            byte[] chunk = Arrays.copyOfRange(all, 0, sendLen);
            String base64 = Base64.encodeToString(chunk, Base64.NO_WRAP);
            JSONObject json = new JSONObject();
            json.put("type", "audio");
            json.put("frame_type", isEndFrame ? 2 : 1);
            json.put("data", base64);
            String message = json.toString();
            Log.d("BLE", "发送" + (isEndFrame ? "结束帧" : "数据帧") + "，长度: " + sendLen + ", 消息长度: " + message.length());
            Log.d("BLE", "当前配置 - 起始帧大小: " + getMinStartFrameSize() + 
                         ", 帧大小: " + getFrameSize() + 
                         ", 发送间隔: " + getSendInterval() + "ms");
            Log.d("BLE", "Base64数据长度: " + base64.length());
            webSocket.send(message);
            lastSendTime = System.currentTimeMillis();
            // 移除已发送数据
            pcmBuffer = new ByteArrayOutputStream();
            pcmBuffer.write(all, sendLen, all.length - sendLen);
            Log.d("BLE", (isEndFrame ? "结束帧" : "数据帧") + "发送成功，剩余数据长度: " + (all.length - sendLen));
        } catch (Exception e) {
            Log.e("BLE", "发送缓冲数据异常", e);
        }
    }

    // 扫描结束后弹窗选择设备
    private void showDeviceSelectDialog() {
        // ⭐ 修复：实现扫描结束后的设备选择弹窗
        if (getActivity() == null) return;
        
        // 检查是否有扫描到的设备
        if (devices.isEmpty()) {
            Toast.makeText(requireContext(), "未扫描到设备", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 创建设备列表
        List<String> deviceList = new ArrayList<>();
        for (BluetoothDevice device : devices) {
            String deviceName = device.getName();
            if (deviceName == null || deviceName.isEmpty()) {
                deviceName = "未知设备";
            }
            deviceList.add(deviceName + "\n" + device.getAddress());
        }
        
        // 创建适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), 
            android.R.layout.simple_list_item_1, deviceList);
        
        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("选择要连接的设备")
               .setAdapter(adapter, (dialog, which) -> {
                   BluetoothDevice selectedDevice = devices.get(which);
                   if (selectedDevice != null) {
                       connectToDevice(selectedDevice);
                   }
               })
               .setNegativeButton("取消", null)
               .show();
    }

    // 连接设备并保存历史
    private void connectToDevice(BluetoothDevice device) {
        if (device == null) return;
        
        // 重置BleManager的用户主动断开标记，允许手动连接
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            bleManager.setUserDisconnected(false);
            Log.d("DeviceFragment", "手动连接设备，重置用户主动断开标记");
        }
        
        // 保存最后连接的设备地址
        SharedPreferences prefs = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        prefs.edit().putString(KEY_LAST_DEVICE, device.getAddress()).apply();
        lastDeviceAddress = device.getAddress();
        
        // ⭐ 修复：检查设备是否已在历史列表中，避免重新添加已删除的设备
        boolean deviceExists = false;
        for (BluetoothDevice historyDevice : historyDeviceList) {
            if (historyDevice.getAddress().equals(device.getAddress())) {
                deviceExists = true;
                break;
            }
        }
        
        // 只有当设备不在历史列表中时才添加
        if (!deviceExists) {
            addDeviceToHistory(device);
        } else {
            Log.d("DeviceFragment", "设备已存在于历史列表中，跳过添加: " + device.getAddress());
        }
        
        // ⭐ 修复：连接成功后停止扫描
        if (isScanning) {
            stopScan();
            Log.d("DeviceFragment", "连接设备，停止扫描");
        }
        
        // 连接设备
        onDeviceClick(device);
    }

    // 弹窗和刷新逻辑
    private void updateDeviceDialog() {
        if (getActivity() == null) return;
        if (deviceAdapterDialog == null) {
            deviceAdapterDialog = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1);
        }
        deviceAdapterDialog.clear();
        for (BluetoothDevice d : foundWhiteListDevices) {
            deviceAdapterDialog.add(d.getName() + "\n" + d.getAddress());
        }
        if (deviceDialog == null) {
            deviceDialog = new AlertDialog.Builder(getActivity())
                .setTitle("选择设备连接")
                .setAdapter(deviceAdapterDialog, (dialog, which) -> {
                    BluetoothDevice device = foundWhiteListDevices.get(which);
                    connectToDevice(device);
                    deviceDialog.dismiss();
                    deviceDialog = null;
                    // ⭐ 修复：连接后清空白名单设备列表，避免重复弹窗
                    foundWhiteListDevices.clear();
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    deviceDialog = null;
                    // ⭐ 修复：取消后也清空白名单设备列表
                    foundWhiteListDevices.clear();
                })
                .create();
            deviceDialog.show();
        } else {
            deviceAdapterDialog.notifyDataSetChanged();
        }
    }

    private void setupHistoryDeviceList() {
        rvHistoryDevices.setLayoutManager(new LinearLayoutManager(requireContext()));
        loadHistoryDevices();
        
        // 添加调试日志
        Log.d("DeviceFragment", "setupHistoryDeviceList - 历史设备数量: " + historyDeviceList.size());
        for (BluetoothDevice device : historyDeviceList) {
            Log.d("DeviceFragment", "历史设备: " + device.getAddress() + " - " + device.getName());
        }
        
        historyDeviceAdapter = new HistoryDeviceAdapter(historyDeviceList,
            address -> {
                Log.d("DeviceFragment", "删除历史设备: " + address);
                removeHistoryDevice(address);
            },
            address -> {
                Log.d("DeviceFragment", "连接历史设备: " + address);
                BluetoothDevice device = getBluetoothDeviceByAddress(address);
                if (device != null) {
                    connectToDevice(device);
                } else {
                    Toast.makeText(requireContext(), "未找到该设备，可能未开机或未在附近", Toast.LENGTH_SHORT).show();
                }
            }
        );
        rvHistoryDevices.setAdapter(historyDeviceAdapter);
        
        // 更新UI显示状态
        updateHistoryDevicesVisibility();
    }

    private void loadHistoryDevices() {
        historyDeviceList.clear();
        
        // ⭐ 修复：统一使用BleManager来管理历史设备
        BleManager bleManager = BleManager.getInstance();
        if (bleManager != null) {
            // 从DeviceFragment的SharedPreferences获取完整的历史设备列表
            SharedPreferences prefs = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            Set<String> addrSet = prefs.getStringSet("history_device_set", new HashSet<>());
            
            Log.d("DeviceFragment", "loadHistoryDevices - 从SharedPreferences加载到 " + addrSet.size() + " 个设备地址");
            
            for (String addr : addrSet) {
                try {
                    BluetoothDevice device = bleManager.getBluetoothAdapter().getRemoteDevice(addr);
                    historyDeviceList.add(device);
                    Log.d("DeviceFragment", "成功加载历史设备: " + addr + " - " + device.getName());
                } catch (Exception e) {
                    Log.e("DeviceFragment", "加载历史设备失败: " + addr, e);
                }
            }
        }
        
        Log.d("DeviceFragment", "loadHistoryDevices - 最终加载了 " + historyDeviceList.size() + " 个历史设备");
    }

    private void saveHistoryDevices() {
        // ⭐ 修复：统一使用BleManager来管理历史设备
        // 历史设备的保存现在由BleManager统一管理，这里只需要更新UI
        Log.d("DeviceFragment", "saveHistoryDevices - 历史设备保存由BleManager统一管理");
        
        // 更新UI显示状态
        updateHistoryDevicesVisibility();
    }

    private void removeHistoryDevice(String address) {
        Log.d("DeviceFragment", "removeHistoryDevice - 开始删除设备: " + address);
        
        // ⭐ 修复：统一使用BleManager来管理历史设备
        // 检查是否是当前连接的设备
        BleManager bleManager = BleManager.getInstance();
        boolean isCurrentlyConnected = false;
        if (bleManager != null && bleManager.isConnected()) {
            BluetoothDevice connectedDevice = bleManager.getConnectedDevice();
            if (connectedDevice != null && connectedDevice.getAddress().equals(address)) {
                isCurrentlyConnected = true;
                Log.d("DeviceFragment", "删除的是当前连接的设备，先断开连接");
                
                // 先断开连接
                bleManager.disconnect();
                
                // 等待一小段时间确保断开完成
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    // 清除UI显示
                    clearConnectedDevice();
                }, 500);
            }
        }
        
        // 从UI列表中移除设备
        for (int i = 0; i < historyDeviceList.size(); i++) {
            if (historyDeviceList.get(i).getAddress().equals(address)) {
                historyDeviceList.remove(i);
                Log.d("DeviceFragment", "removeHistoryDevice - 从UI列表中删除设备");
                break;
            }
        }
        
        // 通知BleManager清除历史设备记录
        if (bleManager != null) {
            bleManager.clearSpecificDeviceAddress(address);
            Log.d("DeviceFragment", "removeHistoryDevice - 通知BleManager清除指定设备地址: " + address);
        }
        
        if (historyDeviceAdapter != null) {
            historyDeviceAdapter.notifyDataSetChanged();
            Log.d("DeviceFragment", "removeHistoryDevice - 通知适配器数据已更改");
        }
        
        // 更新UI显示状态
        updateHistoryDevicesVisibility();
    }

    // 新增：更新历史设备列表的可见性
    private void updateHistoryDevicesVisibility() {
        if (rvHistoryDevices != null) {
            if (historyDeviceList.isEmpty()) {
                Log.d("DeviceFragment", "updateHistoryDevicesVisibility - 历史设备列表为空，隐藏RecyclerView");
                rvHistoryDevices.setVisibility(View.GONE);
            } else {
                Log.d("DeviceFragment", "updateHistoryDevicesVisibility - 历史设备列表有 " + historyDeviceList.size() + " 个设备，显示RecyclerView");
                rvHistoryDevices.setVisibility(View.VISIBLE);
            }
        }
    }

    private BluetoothDevice getBluetoothDeviceByAddress(String address) {
        try {
            // 使用BleManager获取蓝牙适配器
            BleManager bleManager = BleManager.getInstance();
            if (bleManager != null) {
                BluetoothAdapter adapter = bleManager.getBluetoothAdapter();
                if (adapter != null) {
                    return adapter.getRemoteDevice(address);
                }
            }
        } catch (Exception e) {
            Log.e("DeviceFragment", "根据地址获取设备失败: " + address, e);
        }
        return null;
    }

    private boolean isAccessibilityServiceEnabled(Context context, Class<?> service) {
        String prefString = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
        if (prefString == null) return false;
        String serviceId = context.getPackageName() + "/" + service.getName();
        return prefString.contains(serviceId);
    }

    private void handleRecognitionResult(String text, boolean isFinal) {
        // 清除之前的超时任务
        if (recognitionTimeoutRunnable != null) {
            recognitionHandler.removeCallbacks(recognitionTimeoutRunnable);
        }

        // 添加到缓冲区
        recognitionBuffer.append(text);

        // 判断是否是最终结果
        boolean shouldTriggerPaste = isFinal ||
                                   text.endsWith("") ||
                text.endsWith(".") ||
                text.endsWith("。") ||
                                   text.endsWith("？") || 
                                   text.endsWith("！") || 
                                   text.endsWith("\n");

        if (shouldTriggerPaste) {
            // 获取完整结果并清空缓冲区
            String finalResult = recognitionBuffer.toString();
            recognitionBuffer.setLength(0);
            
            // 在主线程中更新UI显示
            requireActivity().runOnUiThread(() -> {
                if (binding != null) {
                   // binding.tvWebsocketResult.setText(finalResult);
                }
            });
            
            // 触发粘贴
            PasteAccessibilityService.triggerPaste(requireContext());
            
            Log.d("DeviceFragment", "触发粘贴，最终结果: " + finalResult);
        } else {
            // 设置超时任务，防止最后一段没有结束符
            recognitionTimeoutRunnable = new Runnable() {
                @Override
                public void run() {
                    if (recognitionBuffer.length() > 0) {
                        String finalResult = recognitionBuffer.toString();
                        recognitionBuffer.setLength(0);
                        
                        // 在主线程中更新UI显示
                        requireActivity().runOnUiThread(() -> {
                            if (binding != null) {
                                //binding.tvWebsocketResult.setText(finalResult);
                            }
                        });
                        
                        // 触发粘贴
                        PasteAccessibilityService.triggerPaste(requireContext());
                        
                        Log.d("DeviceFragment", "超时触发粘贴，最终结果: " + finalResult);
                    }
                }
            };
            recognitionHandler.postDelayed(recognitionTimeoutRunnable, RECOGNITION_TIMEOUT);
        }
    }

    private void onWebSocketMessage(String message) {
        try {
            JSONObject json = new JSONObject(message);
            String text = json.optString("text", "");
            boolean isFinal = json.optBoolean("is_final", false);
            
            handleRecognitionResult(text, isFinal);
        } catch (JSONException e) {
            Log.e("DeviceFragment", "解析WebSocket消息失败", e);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        
        Log.d("DeviceFragment", "onDestroyView被调用");
        
        // 停止扫描
        if (isScanning) {
            stopScan();
        }
        
        // 注意：不主动断开BleManager连接，因为它是前台服务
        // BleManager会保持连接状态
        
        // 停止版本信息更新定时器
        stopVersionUpdateTimer();
        
        // 取消播放超时
        cancelPlaybackTimeout();
        
        // 取消FFF4数据超时
        if (fff4TimeoutRunnable != null) {
            fff4TimeoutHandler.removeCallbacks(fff4TimeoutRunnable);
        }
        
        // 清理音频播放器
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        
        // 清理ASR客户端
        if (asrWsClient != null) {
            asrWsClient.close();
            asrWsClient = null;
        }
        
        Log.d("DeviceFragment", "DeviceFragment视图资源清理完成");
    }

    // 获取设备类型字符串
    private String getDeviceTypeString(int type) {
        switch (type) {
            case BluetoothDevice.DEVICE_TYPE_CLASSIC:
                return "经典蓝牙";
            case BluetoothDevice.DEVICE_TYPE_LE:
                return "低功耗蓝牙";
            case BluetoothDevice.DEVICE_TYPE_DUAL:
                return "双模蓝牙";
            case BluetoothDevice.DEVICE_TYPE_UNKNOWN:
            default:
                return "未知类型";
        }
    }

    // 专门针对双模设备的BLE连接方法（已废弃，统一使用BleManager）
    private void performBLEConnectionForDualMode(BluetoothDevice device) {
        // ⭐ 修复：移除自己的双模式连接逻辑，统一使用BleManager
        // 现在BleManager统一管理连接逻辑
        Log.d("DeviceFragment", "双模式连接由BleManager统一管理");
    }

    // 专门针对双模设备的特征查找和设置方法
    private void findAndSetCharacteristicsForDualMode(BluetoothGatt gatt) {
        // ⭐ 修复：移除自己的双模式特征查找逻辑，统一使用BleManager
        // 现在BleManager统一管理特征查找
        Log.d("DeviceFragment", "双模式特征查找由BleManager统一管理");
    }

    // 专门针对双模设备的顺序使能通知方法
    private void enableNotificationsSequentiallyForDualMode(BluetoothGatt gatt, List<BluetoothGattCharacteristic> characteristics, int index) {
        // ⭐ 修复：移除自己的通知启用逻辑，统一使用BleManager
        // 现在BleManager统一管理通知启用
        Log.d("DeviceFragment", "通知启用由BleManager统一管理");
    }

    // 专门针对双模设备的通知使能重试方法
    private void enableNotificationWithRetryForDualMode(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int retryCount) {
        // ⭐ 修复：移除自己的通知启用重试逻辑，统一使用BleManager
        // 现在BleManager统一管理通知启用
        Log.d("DeviceFragment", "通知启用重试由BleManager统一管理");
    }

    // 获取连接状态字符串
    private String getConnectionStatusString(int status) {
        switch (status) {
            case BluetoothGatt.GATT_SUCCESS:
                return "成功";
            case BluetoothGatt.GATT_FAILURE:
                return "失败";
            case 8:
                return "超时";
            case 19:
                return "设备忙";
            case 22:
                return "设备不可达";
            case 133:
                return "错误";
            default:
                return "未知状态(" + status + ")";
        }
    }

    // 获取连接状态字符串
    private String getConnectionStateString(int state) {
        switch (state) {
            case BluetoothProfile.STATE_DISCONNECTED:
                return "已断开";
            case BluetoothProfile.STATE_CONNECTING:
                return "连接中";
            case BluetoothProfile.STATE_CONNECTED:
                return "已连接";
            case BluetoothProfile.STATE_DISCONNECTING:
                return "断开中";
            default:
                return "未知状态(" + state + ")";
        }
    }

    // 处理FFF4音频数据（无帧头，直接ADPCM数据）
    private void handleFFF4AudioData(byte[] adpcmData) {
        if (adpcmData == null || adpcmData.length == 0) {
            Log.w("BLE", "FFF4音频数据为空");
            return;
        }
        
        Log.d("BLE", "开始处理FFF4音频数据，长度: " + adpcmData.length + " 字节");
        
        // 1. 将ADPCM数据追加到缓冲区
        try {
            fff4AdpcmBuffer.write(adpcmData);
            Log.d("BLE", "FFF4 ADPCM数据已追加到缓冲区，当前缓冲区大小: " + fff4AdpcmBuffer.size() + " 字节");
        } catch (Exception e) {
            Log.e("BLE", "FFF4 ADPCM数据写入缓冲区异常", e);
            return;
        }
        
        // 2. 更新最后接收数据时间
        lastFFF4DataTime = System.currentTimeMillis();
        
        // 3. 取消之前的超时任务
        if (fff4TimeoutRunnable != null) {
            fff4TimeoutHandler.removeCallbacks(fff4TimeoutRunnable);
        }
        
        // 4. 设置新的超时任务
        fff4TimeoutRunnable = new Runnable() {
            @Override
            public void run() {
                Log.d("BLE", "FFF4数据接收超时，开始处理完整音频数据");
                processCompleteFFF4Audio();
            }
        };
        fff4TimeoutHandler.postDelayed(fff4TimeoutRunnable, FFF4_DATA_TIMEOUT);
    }
    
    // 处理完整的FFF4音频数据
    private void processCompleteFFF4Audio() {
        try {
            // 1. 获取完整的ADPCM数据
            byte[] completeAdpcm = fff4AdpcmBuffer.toByteArray();
            if (completeAdpcm.length == 0) {
                Log.w("BLE", "FFF4 ADPCM缓冲区为空，跳过处理");
                return;
            }
            
            Log.d("BLE", "开始处理完整FFF4音频数据，ADPCM长度: " + completeAdpcm.length + " 字节");
            
            // 2. 进行ADPCM解码（无帧头，8K采样率）
            short[] pcmSamples = adpcmDecoder.decodeWithoutHeader(completeAdpcm);
            byte[] pcmData = shortArrayToByteArray(pcmSamples);
            
            Log.d("BLE", "FFF4 ADPCM解码完成，PCM长度: " + pcmData.length + " 字节，采样数: " + pcmSamples.length);
            Log.d("BLE", "FFF4音频采样率: " + PCM_SAMPLE_RATE + " Hz，声道数: " + PCM_CHANNELS + "，位深: " + PCM_BITS + " bit");
            
            // 3. 保存PCM数据到文件
            saveFFF4PcmFile(pcmData);
            
            // 4. 保存PCM数据到WAV文件
            saveFFF4PcmAsWav(pcmData);
            
            // 5. 播放音频
            playFFF4Audio(pcmData);
            
            // 6. 清空缓冲区
            fff4AdpcmBuffer.reset();
            fff4PcmBuffer.reset();
            
            Log.d("BLE", "FFF4音频数据处理完成");
            
        } catch (Exception e) {
            Log.e("BLE", "处理FFF4音频数据异常", e);
        }
    }
    
    // 保存FFF4 PCM数据为WAV文件
    private void saveFFF4PcmAsWav(byte[] pcmData) {
        try {
            byte[] wav = WavUtil.pcmToWav(pcmData, PCM_SAMPLE_RATE, PCM_CHANNELS, PCM_BITS);
            // 保存到外部存储的包名目录下，使用固定文件名（新文件替换旧文件）
            File wavFile = new File(requireContext().getExternalFilesDir(null), "fff4_audio.wav");
            FileOutputStream fos = new FileOutputStream(wavFile);
            fos.write(wav);
            fos.close();
            Log.d("BLE", "FFF4 WAV文件已保存: " + wavFile.getAbsolutePath());
        } catch (Exception e) {
            Log.e("BLE", "保存FFF4 WAV文件异常", e);
        }
    }
    
    // 保存FFF4 PCM数据为PCM文件
    private void saveFFF4PcmFile(byte[] pcmData) {
        try {
            // 保存到外部存储的包名目录下，使用固定文件名（新文件替换旧文件）
            File pcmFile = new File(requireContext().getExternalFilesDir(null), "fff4_audio.pcm");
            FileOutputStream fos = new FileOutputStream(pcmFile);
            fos.write(pcmData);
            fos.close();
            Log.d("BLE", "FFF4 PCM文件已保存: " + pcmFile.getAbsolutePath());
            Log.d("BLE", "FFF4 PCM文件大小: " + pcmData.length + " 字节");
        } catch (Exception e) {
            Log.e("BLE", "保存FFF4 PCM文件异常", e);
        }
    }
    
    // 播放FFF4音频数据
    private void playFFF4Audio(byte[] pcmData) {
        try {
            // 1. 将PCM数据转换为WAV格式
            byte[] wav = WavUtil.pcmToWav(pcmData, PCM_SAMPLE_RATE, PCM_CHANNELS, PCM_BITS);
            
            // 2. 保存为固定文件（新文件替换旧文件）
            File fff4WavFile = new File(requireContext().getExternalFilesDir(null), "fff4_audio.wav");
            FileOutputStream fos = new FileOutputStream(fff4WavFile);
            fos.write(wav);
            fos.close();
            
            // 3. 播放音频
            if (mediaPlayer != null) {
                mediaPlayer.release();
            }
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(fff4WavFile.getAbsolutePath());
            mediaPlayer.prepare();
            mediaPlayer.start();
            
            Log.d("BLE", "开始播放FFF4音频，PCM长度: " + pcmData.length + " 字节");
            Log.d("BLE", "FFF4音频文件已保存: " + fff4WavFile.getAbsolutePath());
            
            // 4. 播放完成后的处理（不删除文件，保留供下次替换）
            mediaPlayer.setOnCompletionListener(mp -> {
                Log.d("BLE", "FFF4音频播放完成，文件保留: " + fff4WavFile.getAbsolutePath());
            });
            
                            } catch (Exception e) {
            Log.e("BLE", "播放FFF4音频异常", e);
        }
    }

    // 发送心跳
    private void sendHeartbeat() {
        if (webSocket != null && isWsConnected) {
            try {
                JSONObject heartbeat = new JSONObject();
                heartbeat.put("type", "heartbeat");
                webSocket.send(heartbeat.toString());
                Log.d("BLE", "发送心跳包");
            } catch (Exception e) {
                Log.e("BLE", "发送心跳包异常", e);
            }
        }
    }
    
    // 启动心跳
    private void startHeartbeat() {
        if (heartbeatRunnable != null) {
            heartbeatHandler.removeCallbacks(heartbeatRunnable);
        }
        heartbeatRunnable = new Runnable() {
            @Override
            public void run() {
                sendHeartbeat();
                heartbeatHandler.postDelayed(this, HEARTBEAT_INTERVAL);
            }
        };
        heartbeatHandler.postDelayed(heartbeatRunnable, HEARTBEAT_INTERVAL);
        Log.d("BLE", "心跳机制已启动，间隔: " + HEARTBEAT_INTERVAL + "ms");
    }
    
    // 停止心跳
    private void stopHeartbeat() {
        if (heartbeatRunnable != null) {
            heartbeatHandler.removeCallbacks(heartbeatRunnable);
            heartbeatRunnable = null;
            Log.d("BLE", "心跳机制已停止");
        }
    }

    // 设置播放超时
    private void setupPlaybackTimeout() {
        // 取消之前的超时任务
        cancelPlaybackTimeout();
        
        // 设置新的超时任务
        playbackTimeoutRunnable = new Runnable() {
            @Override
            public void run() {
                Log.d("BLE", "播放超时触发，开始播放当前累积的音频数据");
                playCurrentAudioData();
            }
        };
        playbackTimeoutHandler.postDelayed(playbackTimeoutRunnable, PLAYBACK_TIMEOUT);
        Log.d("BLE", "设置播放超时，将在" + PLAYBACK_TIMEOUT + "ms后触发");
    }
    
    // 取消播放超时
    private void cancelPlaybackTimeout() {
        if (playbackTimeoutRunnable != null) {
            playbackTimeoutHandler.removeCallbacks(playbackTimeoutRunnable);
            playbackTimeoutRunnable = null;
            Log.d("BLE", "取消播放超时");
        }
    }
    
    // 播放当前累积的音频数据
    private void playCurrentAudioData() {
        try {
            byte[] currentPcm = wavPcmBuffer.toByteArray();
            if (currentPcm.length > 0) {
                Log.d("BLE", "播放超时触发，当前PCM数据长度: " + currentPcm.length + " 字节");
                savePcmAsWav(currentPcm, true); // 标记为超时播放
                wavPcmBuffer.reset();
            } else {
                Log.w("BLE", "播放超时触发，但当前PCM缓冲区为空");
            }
        } catch (Exception e) {
            Log.e("BLE", "播放超时处理异常", e);
        }
    }

    // 根据宏控制选择ASR客户端初始化方法
    private void initAsrClient() {
        if (!USE_ASR_CLIENT) {
            return; // 如果未启用ASR客户端，直接返回
        }
        
        // 如果已经连接，不需要重新初始化
        if (isAsrConnected) {
            Log.d("BLE", "ASR客户端已连接，跳过初始化");
            return;
        }
        
        // 如果客户端存在但未连接，先关闭
        if (asrWsClient != null) {
            asrWsClient.close();
            asrWsClient = null;
        }
        
        // 创建新的ASR客户端
        asrWsClient = new AsrWsClient();
        asrWsClient.setCallback(new AsrWsClient.AsrWsCallback() {
            @Override
            public void onConnected() {
                Log.d("BLE", "ASR WebSocket连接成功");
                isAsrConnected = true;
                // 重置音频缓冲区
                asrWsClient.resetAudioBuffer();
                // 发送初始请求
                asrWsClient.sendInitialRequest();
                // 更新UI状态 - 检查Fragment是否还附加到Activity
                if (isAdded()) {
                    requireActivity().runOnUiThread(() -> {
                        //updateWebSocketStatus();
                    });
                }
            }
            
            @Override
            public void onInitialRequestSent() {
                Log.d("BLE", "ASR初始请求发送完成");
            }
            
            @Override
            public void onMessage(String text, boolean isFinal) {
                Log.d("BLE", "ASR识别结果: " + text + ", isFinal: " + isFinal);
                // 检查Fragment是否还附加到Activity
                if (isAdded()) {
                    handleRecognitionResult(text, isFinal);
                }
            }
            
            @Override
            public void onError(String error) {
                Log.e("BLE", "ASR WebSocket错误: " + error);
                isAsrConnected = false;
                // 更新UI状态 - 检查Fragment是否还附加到Activity
                if (isAdded()) {
                    requireActivity().runOnUiThread(() -> {
                        //updateWebSocketStatus();
                    });
                }
            }
            
            @Override
            public void onClosed() {
                Log.d("BLE", "ASR WebSocket连接关闭");
                isAsrConnected = false;
                // 更新UI状态 - 检查Fragment是否还附加到Activity
                if (isAdded()) {
                    requireActivity().runOnUiThread(() -> {
                        //updateWebSocketStatus();
                    });
                }
            }
        });
        
        // 连接ASR WebSocket
        Log.d("BLE", "开始连接ASR WebSocket");
        asrWsClient.connect();
    }

    /**
     * 执行编码测试
     */
//    private void performEncodeTest() {
//        if (lastPcmData == null || lastPcmData.length == 0) {
//            Toast.makeText(requireContext(), "没有PCM数据可编码", Toast.LENGTH_SHORT).show();
//            return;
//        }
//
//        try {
//            // 打印原始PCM数据
//            Log.d("ADPCM", "=== 编码测试原始PCM数据 ===");
//            Log.d("ADPCM", "PCM数据长度: " + lastPcmData.length + " 字节");
//            Log.d("ADPCM", "PCM十六进制数据(前40字节): " + bytesToHex(Arrays.copyOfRange(lastPcmData, 0, Math.min(40, lastPcmData.length))));
//            Log.d("ADPCM", "=== PCM数据结束 ===");
//
//            // 保存原始PCM数据到文件
//            saveTestPcmFile(lastPcmData, "test_original_pcm.pcm");
//
//            // 重置编码器状态
//            testEncoder.reset();
//
//            // 编码PCM数据为ADPCM
//            encodedAdpcmData = testEncoder.encodeFromBytes(lastPcmData);
//
//            // 保存编码后的ADPCM数据到文件
//            saveTestAdpcmFile(encodedAdpcmData, "test_encoded_adpcm.adpcm");
//
//            // 模拟流式编码过程，对比结果
//            performStreamingEncodeTest(lastPcmData);
//
//            // 打印编码后的ADPCM数据
//            Log.d("ADPCM", "=== 编码测试ADPCM数据 ===");
//            Log.d("ADPCM", "ADPCM数据长度: " + encodedAdpcmData.length + " 字节");
//            Log.d("ADPCM", "ADPCM十六进制数据(前40字节): " + bytesToHex(Arrays.copyOfRange(encodedAdpcmData, 0, Math.min(40, encodedAdpcmData.length))));
//            Log.d("ADPCM", "=== ADPCM数据结束 ===");
//
//            // 显示编码结果
//            String result = String.format("编码完成: PCM %d 字节 -> ADPCM %d 字节 (压缩比: %.2f:1)",
//                lastPcmData.length, encodedAdpcmData.length,
//                (float) lastPcmData.length / encodedAdpcmData.length);
//
//            tvEncodingStatus.setText(result);
//            btnDecodeTest.setEnabled(true);
//
//            // 显示文件保存路径
//            File externalDir = requireContext().getExternalFilesDir(null);
//            String filePath = externalDir != null ? externalDir.getAbsolutePath() : "未知路径";
//            Toast.makeText(requireContext(), "编码测试完成，文件已保存到: " + filePath, Toast.LENGTH_LONG).show();
//            Log.d("ADPCM", "编码测试完成: " + result);
//
//        } catch (Exception e) {
//            Log.e("ADPCM", "编码测试失败", e);
//            Toast.makeText(requireContext(), "编码测试失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
//        }
//    }
//
//    /**
//     * 执行解码测试
//     */
//    private void performDecodeTest() {
//        if (encodedAdpcmData == null || encodedAdpcmData.length == 0) {
//            Toast.makeText(requireContext(), "没有ADPCM数据可解码", Toast.LENGTH_SHORT).show();
//            return;
//        }
//
//        try {
//            // 打印原始ADPCM数据
//            Log.d("ADPCM", "=== 解码测试原始ADPCM数据 ===");
//            Log.d("ADPCM", "ADPCM数据长度: " + encodedAdpcmData.length + " 字节");
//            Log.d("ADPCM", "ADPCM十六进制数据(前40字节): " + bytesToHex(Arrays.copyOfRange(encodedAdpcmData, 0, Math.min(40, encodedAdpcmData.length))));
//            Log.d("ADPCM", "=== ADPCM数据结束 ===");
//
//            // 重置解码器状态
//            testDecoder.reset();
//
//            // 解码ADPCM数据为PCM
//            short[] decodedPcm = testDecoder.decode(encodedAdpcmData);
//            byte[] decodedPcmBytes = shortArrayToByteArray(decodedPcm);
//
//            // 保存解码后的PCM数据到文件
//            saveTestPcmFile(decodedPcmBytes, "test_decoded_pcm.pcm");
//
//            // 保存解码后的PCM数据为WAV文件
//            saveTestPcmAsWav(decodedPcmBytes, "test_decoded_audio.wav");
//
//            // 打印解码后的PCM数据
//            Log.d("ADPCM", "=== 解码测试PCM数据 ===");
//            Log.d("ADPCM", "解码PCM数据长度: " + decodedPcmBytes.length + " 字节");
//            Log.d("ADPCM", "解码PCM十六进制数据(前40字节): " + bytesToHex(Arrays.copyOfRange(decodedPcmBytes, 0, Math.min(40, decodedPcmBytes.length))));
//            Log.d("ADPCM", "=== 解码PCM数据结束 ===");
//
//            // 显示解码结果
//            String result = String.format("解码完成: ADPCM %d 字节 -> PCM %d 字节",
//                encodedAdpcmData.length, decodedPcmBytes.length);
//
//            tvEncodingStatus.setText(result);
//
//            // 播放解码后的音频
//            playDecodedAudio(decodedPcmBytes);
//
//            // 显示文件保存路径
//            File externalDir = requireContext().getExternalFilesDir(null);
//            String filePath = externalDir != null ? externalDir.getAbsolutePath() : "未知路径";
//            Toast.makeText(requireContext(), "解码测试完成，文件已保存到: " + filePath + "，正在播放音频", Toast.LENGTH_LONG).show();
//            Log.d("ADPCM", "解码测试完成: " + result);
//
//        } catch (Exception e) {
//            Log.e("ADPCM", "解码测试失败", e);
//            Toast.makeText(requireContext(), "解码测试失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
//        }
//    }
//
//    /**
//     * 播放解码后的音频
//     */
//    private void playDecodedAudio(byte[] pcmData) {
//        try {
//            // 初始化AudioTrack
//            if (testAudioTrack == null) {
//                int bufferSize = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
//                testAudioTrack = new AudioTrack(
//                    AudioManager.STREAM_MUSIC,
//                    8000,
//                    AudioFormat.CHANNEL_OUT_MONO,
//                    AudioFormat.ENCODING_PCM_16BIT,
//                    bufferSize,
//                    AudioTrack.MODE_STREAM
//                );
//            }
//
//            // 播放音频
//            testAudioTrack.play();
//            int written = testAudioTrack.write(pcmData, 0, pcmData.length);
//            Log.d("ADPCM", "播放解码音频: " + written + "/" + pcmData.length + " 字节");
//
//        } catch (Exception e) {
//            Log.e("ADPCM", "播放解码音频失败", e);
//            Toast.makeText(requireContext(), "播放音频失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
//        }
//    }
//
//    /**
//     * 保存测试PCM数据到文件
//     */
//    private void saveTestPcmFile(byte[] pcmData, String fileName) {
//        try {
//            File externalDir = requireContext().getExternalFilesDir(null);
//            if (externalDir == null) {
//                Log.e("ADPCM", "无法获取外部存储目录");
//                return;
//            }
//
//            File pcmFile = new File(externalDir, fileName);
//            FileOutputStream fos = new FileOutputStream(pcmFile);
//            fos.write(pcmData);
//            fos.close();
//
//            Log.d("ADPCM", "测试PCM文件已保存: " + pcmFile.getAbsolutePath());
//            Log.d("ADPCM", "PCM文件大小: " + pcmData.length + " 字节");
//
//        } catch (Exception e) {
//            Log.e("ADPCM", "保存测试PCM文件失败: " + e.getMessage(), e);
//        }
//    }
//
//    /**
//     * 保存测试ADPCM数据到文件
//     */
//    private void saveTestAdpcmFile(byte[] adpcmData, String fileName) {
//        try {
//            File externalDir = requireContext().getExternalFilesDir(null);
//            if (externalDir == null) {
//                Log.e("ADPCM", "无法获取外部存储目录");
//                return;
//            }
//
//            File adpcmFile = new File(externalDir, fileName);
//            FileOutputStream fos = new FileOutputStream(adpcmFile);
//            fos.write(adpcmData);
//            fos.close();
//
//            Log.d("ADPCM", "测试ADPCM文件已保存: " + adpcmFile.getAbsolutePath());
//            Log.d("ADPCM", "ADPCM文件大小: " + adpcmData.length + " 字节");
//
//        } catch (Exception e) {
//            Log.e("ADPCM", "保存测试ADPCM文件失败: " + e.getMessage(), e);
//        }
//    }
//
//    /**
//     * 保存测试PCM数据为WAV文件
//     */
//    private void saveTestPcmAsWav(byte[] pcmData, String fileName) {
//        try {
//            File externalDir = requireContext().getExternalFilesDir(null);
//            if (externalDir == null) {
//                Log.e("ADPCM", "无法获取外部存储目录");
//                return;
//            }
//
//            // 转换为WAV格式
//            byte[] wav = WavUtil.pcmToWav(pcmData, 8000, 1, 16);
//
//            File wavFile = new File(externalDir, fileName);
//            FileOutputStream fos = new FileOutputStream(wavFile);
//            fos.write(wav);
//            fos.close();
//
//            Log.d("ADPCM", "测试WAV文件已保存: " + wavFile.getAbsolutePath());
//            Log.d("ADPCM", "WAV文件大小: " + wav.length + " 字节");
//
//        } catch (Exception e) {
//            Log.e("ADPCM", "保存测试WAV文件失败: " + e.getMessage(), e);
//        }
//    }
//
//    /**
//     * 保存实时编码的ADPCM数据到文件
//     */
//    private void saveRealtimeAdpcmFile(byte[] adpcmData) {
//        try {
//            File externalDir = requireContext().getExternalFilesDir(null);
//            if (externalDir == null) {
//                Log.e("ADPCM", "无法获取外部存储目录");
//                return;
//            }
//
//            // 使用追加模式保存实时编码数据
//            File realtimeFile = new File(externalDir, "realtime_encoded_adpcm.adpcm");
//            FileOutputStream fos = new FileOutputStream(realtimeFile, true);
//            fos.write(adpcmData);
//            fos.close();
//
//            Log.d("ADPCM", "实时编码ADPCM数据已追加到文件: " + realtimeFile.getAbsolutePath());
//            Log.d("ADPCM", "本次追加数据: " + adpcmData.length + " 字节");
//
//        } catch (Exception e) {
//            Log.e("ADPCM", "保存实时编码ADPCM文件失败: " + e.getMessage(), e);
//        }
//    }
//
//    /**
//     * 清空实时编码ADPCM文件
//     */
//    private void clearRealtimeAdpcmFile() {
//        try {
//            File externalDir = requireContext().getExternalFilesDir(null);
//            if (externalDir == null) {
//                Log.e("ADPCM", "无法获取外部存储目录");
//                return;
//            }
//
//            File realtimeFile = new File(externalDir, "realtime_encoded_adpcm.adpcm");
//            if (realtimeFile.exists()) {
//                realtimeFile.delete();
//                Log.d("ADPCM", "已清空实时编码ADPCM文件: " + realtimeFile.getAbsolutePath());
//            }
//
//        } catch (Exception e) {
//            Log.e("ADPCM", "清空实时编码ADPCM文件失败: " + e.getMessage(), e);
//        }
//    }
//
//    /**
//     * 保存实际发送给BLE的ADPCM数据到文件
//     */
//    private void saveBleSentAdpcmFile(byte[] adpcmData) {
//        try {
//            File externalDir = requireContext().getExternalFilesDir(null);
//            if (externalDir == null) {
//                Log.e("ADPCM", "无法获取外部存储目录");
//                return;
//            }
//
//            // 使用追加模式保存BLE发送的数据
//            File bleSentFile = new File(externalDir, "ble_sent_adpcm.adpcm");
//            FileOutputStream fos = new FileOutputStream(bleSentFile, true);
//            fos.write(adpcmData);
//            fos.close();
//
//            Log.d("ADPCM", "BLE发送ADPCM数据已追加到文件: " + bleSentFile.getAbsolutePath());
//            Log.d("ADPCM", "本次发送数据: " + adpcmData.length + " 字节");
//
//        } catch (Exception e) {
//            Log.e("ADPCM", "保存BLE发送ADPCM文件失败: " + e.getMessage(), e);
//        }
//    }
//
//    /**
//     * 清空BLE发送ADPCM文件
//     */
//    private void clearBleSentAdpcmFile() {
//        try {
//            File externalDir = requireContext().getExternalFilesDir(null);
//            if (externalDir == null) {
//                Log.e("ADPCM", "无法获取外部存储目录");
//                return;
//            }
//
//            File bleSentFile = new File(externalDir, "ble_sent_adpcm.adpcm");
//            if (bleSentFile.exists()) {
//                bleSentFile.delete();
//                Log.d("ADPCM", "已清空BLE发送ADPCM文件: " + bleSentFile.getAbsolutePath());
//            }
//
//        } catch (Exception e) {
//            Log.e("ADPCM", "清空BLE发送ADPCM文件失败: " + e.getMessage(), e);
//        }
//    }
//
//    /**
//     * 模拟流式编码过程，用于对比测试
//     */
//    private void performStreamingEncodeTest(byte[] pcmData) {
//         try {
//            Log.d("ADPCM", "=== 开始模拟流式编码测试 ===");
//
//            // 创建新的编码器实例，模拟流式编码
//            AdpcmEncoder streamingEncoder = new AdpcmEncoder();
//            // 只在开始时重置一次，保持状态连续性
//            streamingEncoder.reset();
//
//            // 模拟分块处理PCM数据（每320字节一块）
//            ByteArrayOutputStream streamingResult = new ByteArrayOutputStream();
//            int chunkSize = 320; // 改为320字节
//
//            for (int offset = 0; offset < pcmData.length; offset += chunkSize) {
//                int length = Math.min(chunkSize, pcmData.length - offset);
//                byte[] chunk = Arrays.copyOfRange(pcmData, offset, offset + length);
//
//                Log.d("ADPCM", "处理PCM块: 偏移=" + offset + ", 长度=" + length + " 字节");
//
//                // 编码这个块（不重置编码器状态，保持连续性）
//                byte[] adpcmChunk = streamingEncoder.encodeFromBytes(chunk);
//                streamingResult.write(adpcmChunk);
//
//                Log.d("ADPCM", "PCM块编码完成: " + length + " -> " + adpcmChunk.length + " 字节");
//            }
//
//            byte[] streamingAdpcm = streamingResult.toByteArray();
//
//            // 保存流式编码结果
//            saveTestAdpcmFile(streamingAdpcm, "test_streaming_encoded_adpcm.adpcm");
//
//            Log.d("ADPCM", "=== 流式编码测试结果 ===");
//            Log.d("ADPCM", "流式编码ADPCM长度: " + streamingAdpcm.length + " 字节");
//            Log.d("ADPCM", "整段编码ADPCM长度: " + encodedAdpcmData.length + " 字节");
//            Log.d("ADPCM", "长度是否一致: " + (streamingAdpcm.length == encodedAdpcmData.length));
//
//            // 比较前40字节
//            int compareLength = Math.min(40, Math.min(streamingAdpcm.length, encodedAdpcmData.length));
//            String streamingHex = bytesToHex(Arrays.copyOfRange(streamingAdpcm, 0, compareLength));
//            String normalHex = bytesToHex(Arrays.copyOfRange(encodedAdpcmData, 0, compareLength));
//            Log.d("ADPCM", "流式编码前40字节: " + streamingHex);
//            Log.d("ADPCM", "整段编码前40字节: " + normalHex);
//            Log.d("ADPCM", "前40字节是否一致: " + streamingHex.equals(normalHex));
//
//            Log.d("ADPCM", "=== 流式编码测试结束 ===");
//
//        } catch (Exception e) {
//            Log.e("ADPCM", "流式编码测试失败", e);
//        }
//    }

    /**
     * 添加设备到历史列表
     */
    private void addDeviceToHistory(BluetoothDevice device) {
        if (device == null) {
            Log.w("DeviceFragment", "addDeviceToHistory - 设备为空，跳过添加");
            return;
        }
        
        Log.d("DeviceFragment", "addDeviceToHistory - 开始添加设备: " + device.getAddress() + " - " + device.getName());
        
        // ⭐ 修复：统一使用BleManager来管理历史设备
        // 历史设备的保存现在由BleManager统一管理，这里只需要更新UI显示
        
        // 检查设备是否已经在历史列表中
        for (BluetoothDevice d : historyDeviceList) {
            if (d.getAddress().equals(device.getAddress())) {
                Log.d("DeviceFragment", "addDeviceToHistory - 设备已存在于历史列表中，跳过添加");
                return;
            }
        }
        
        // 添加设备到历史列表（仅用于UI显示）
        historyDeviceList.add(device);
        Log.d("DeviceFragment", "addDeviceToHistory - 设备已添加到历史列表，当前数量: " + historyDeviceList.size());
        
        // 更新适配器
        if (historyDeviceAdapter != null) {
            historyDeviceAdapter.notifyDataSetChanged();
            Log.d("DeviceFragment", "addDeviceToHistory - 通知适配器数据已更改");
        }
        
        // 更新UI显示状态
        updateHistoryDevicesVisibility();
        
        Log.d("DeviceFragment", "addDeviceToHistory - 设备添加完成: " + device.getAddress());
    }

    /**
     * 保存最后连接的设备地址到BleManager
     */
    private void saveLastDeviceAddress(String address) {
        // ⭐ 修复：统一使用BleManager来管理历史设备地址
        // 历史设备地址的保存现在由BleManager统一管理
        Log.d("DeviceFragment", "saveLastDeviceAddress - 历史设备地址保存由BleManager统一管理: " + address);
    }

    /**
     * 注册电池电量广播接收器
     */
    private void registerBatteryLevelReceiver() {
        // 不再需要广播接收器，直接从BleManager获取数据
        Log.d("DeviceFragment", "电池电量显示改为直接从BleManager获取");
    }
    
    /**
     * 更新电池电量显示
     */
    private void updateBatteryLevelDisplay() {
        try {
            BleManager bleManager = BleManager.getInstance();
            if (bleManager != null) {
                // 检查BLE连接状态
                if (!bleManager.isConnected()) {
                    Log.w("DeviceFragment", "BLE未连接，跳过电池电量更新");
                    tvConnectedDeviceBatteryLevel.setText("当前电量：未连接");
                    return;
                }
                
                int batteryLevel = bleManager.getBatteryLevel();
                long lastUpdateTime = bleManager.getLastBatteryUpdateTime();
                
                Log.d("DeviceFragment", "获取电池电量: " + batteryLevel + "%, 更新时间: " + lastUpdateTime);
                
                if (batteryLevel >= 0) {
                    String timeStr = "";
                    if (lastUpdateTime > 0) {
                        long timeDiff = System.currentTimeMillis() - lastUpdateTime;
                        if (timeDiff < 60000) { // 1分钟内
                            timeStr = " (刚刚更新)";
                        } else if (timeDiff < 300000) { // 5分钟内
                            timeStr = " (" + (timeDiff / 60000) + "分钟前)";
                        } else {
                            timeStr = " (" + (timeDiff / 60000) + "分钟前)";
                        }
                    }
                    String displayText = "当前电量：" + batteryLevel + "%" + timeStr;
                    tvConnectedDeviceBatteryLevel.setText(displayText);
                    Log.d("DeviceFragment", "电池电量显示已更新: " + displayText);
                } else {
                    tvConnectedDeviceBatteryLevel.setText("当前电量：获取中...");
                    Log.d("DeviceFragment", "电池电量未获取，尝试重新读取");
                    // 尝试重新读取电池电量
                    bleManager.readBatteryLevel();
                }
            } else {
                tvConnectedDeviceBatteryLevel.setText("当前电量：BleManager未初始化");
                Log.w("DeviceFragment", "BleManager未初始化");
            }
        } catch (Exception e) {
            Log.e("DeviceFragment", "更新电池电量显示失败", e);
            tvConnectedDeviceBatteryLevel.setText("当前电量：获取失败");
        }
    }

    /**
     * 手动刷新电池电量显示
     */
    public void refreshBatteryLevel() {
        Log.d("DeviceFragment", "手动刷新电池电量显示");
        updateBatteryLevelDisplay();
    }
    
    /**
     * 电池电量更新监听器回调
     */
    @Override
    public void onBatteryLevelUpdated(int batteryLevel, long timestamp) {
        Log.d("DeviceFragment", "收到电池电量更新通知: " + batteryLevel + "%, 时间: " + timestamp);
        if (isAdded()) {
            requireActivity().runOnUiThread(() -> {
                updateBatteryLevelDisplay();
            });
        }
    }

    @Override
    public void onScanResult(BluetoothDevice device, int rssi) {
        if (!isAdded()) {
            return;
        }
        
        Log.d("DeviceFragment", "收到BleManager扫描结果: " + device.getAddress() + " - " + device.getName() + ", RSSI: " + rssi);
        
        // ⭐ 修复：只有白名单设备才添加到devices列表
        if (shouldAddDevice(device)) {
            // 将扫描到的设备添加到devices列表
            boolean exists = false;
            for (BluetoothDevice d : devices) {
                if (d.getAddress().equals(device.getAddress())) {
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                devices.add(device);
                Log.d("DeviceFragment", "白名单设备已添加到devices列表: " + device.getAddress());
            }
            
            // ⭐ 修复：检查是否已经在白名单列表中，避免重复弹窗
            boolean existsInWhiteList = false;
            for (BluetoothDevice d : foundWhiteListDevices) {
                if (d.getAddress().equals(device.getAddress())) {
                    existsInWhiteList = true;
                    Log.d("DeviceFragment", "设备已在白名单列表中，跳过弹窗: " + device.getAddress());
                    break;
                }
            }
            if (!existsInWhiteList) {
                foundWhiteListDevices.add(device);
                Log.d("DeviceFragment", "设备已添加到白名单列表，准备弹窗: " + device.getAddress());
                if (isAdded()) {
                    requireActivity().runOnUiThread(() -> {
                        updateDeviceDialog();
                    });
                }
            }
            
            // 更新UI
            if (isAdded()) {
                requireActivity().runOnUiThread(() -> {
                    if (deviceAdapter != null) {
                        deviceAdapter.notifyDataSetChanged();
                    }
                    updateNoDevicesVisibility();
                });
            }
        } else {
            Log.d("DeviceFragment", "非白名单设备，跳过添加: " + device.getAddress() + " - " + device.getName());
        }
    }
    
    @Override
    public void onScanFailed(int errorCode) {
        Log.e("DeviceFragment", "BleManager扫描失败，错误码: " + errorCode);
        if (isAdded()) {
            requireActivity().runOnUiThread(() -> {
                isScanning = false;
                btnScanDevices.setText("扫描设备");
                updateNoDevicesVisibility();
            });
        }
    }

} 
